C# - If statement - Unreachable code detected?

Schravendeel

Newcomer
Joined
Dec 22, 2009
Messages
2
Hello,

The line "result._response = LoginResult.INVALID_REQUEST;" throws an Unreachable code detected warning. What am I doing wrong?

Code:
[WebMethod]
        public LoginResponse Authenticate(string username, string passwordmd5){
            LoginResponse result = new LoginResponse();
            if (DataBaseManager.CheckIPBan(Context.Request.UserHostAddress))
            {
                result._response = LoginResult.IP_BANNED;
            }
            else
            {
                if (MAINTENANCE_MODE)
                {
                    result._response = LoginResult.MAINTENANCE_MODE;
                }
                else
                {
                    result._response = LoginResult.INVALID_REQUEST;
                }
            }

            return result;
        }
 
Is MAINTENANCE_MODE a constant? If so, it would be the same as typing:
Code:
                if (true)
                {
                    result._response = LoginResult.MAINTENANCE_MODE;
                }
                else
                {
                    result._response = LoginResult.INVALID_REQUEST;
                }
The compiler is just clever enough to realize that only one block of the if statement can ever be executed. The other block is unreachable.

One alternative would be to define a symbol used for conditional compilation.

Code:
[WebMethod]
[COLOR="Blue"]#define MAINTENANCE[/COLOR] // Omit for non-maintenance build

        public LoginResponse Authenticate(string username, string passwordmd5){
            LoginResponse result = new LoginResponse();
            if (DataBaseManager.CheckIPBan(Context.Request.UserHostAddress))
            {
                result._response = LoginResult.IP_BANNED;
            }
            else
            {
[COLOR="Blue"]#if(MAINTENANCE)[/COLOR]
                    result._response = LoginResult.MAINTENANCE_MODE;
[COLOR="Blue"]#else[/COLOR]
                    result._response = LoginResult.INVALID_REQUEST;
[COLOR="Blue"]#endif[/COLOR]
            }

            return result;
        }

Another alternative would be to suppress the warning for the code in question.
 
Back
Top