Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation of C# constant expression by VS.NET 2010

When I tried a sample expression in C# in Visual Studio

public int Test()
{
    if (10/2 == 5)
        throw new Exception();
    return 0;
}

When I keep the expression 10/2 == 5, the vs.net automatically throws a warning "Unreachable Code Detected".

If I change the expression 10/2 == 6, the IDE is happy? How does it happen?

Edited: Sorry for the incomplete question. It happens so instantly and happens even before compiling the code?

I have upvoted each of the replies and accepted the first answer on FIFO basis

like image 290
NSN Avatar asked Aug 14 '12 14:08

NSN


2 Answers

if (10/2 == 5)

Will always return true, which means

throw new Exception();

Will always be executed, and

return 0;

Will never be reached

like image 150
Thomas Avatar answered Oct 04 '22 02:10

Thomas


As others have said, the compiler can evaluate the expression 10 / 2 == 5 compile-time because it's a constant expression. It evaluates to true, therefore any code after the if scope is unreacable. If changed to false, the code inside the if is unreachable.

So now consider this code:

public int TestA() 
{ 
    if (10 / 2 == 5) 
        return 1; 
    return 0; 
} 

public int TestB() 
{ 
    if (10 / 2 == 6) 
        return 1; 
    return 0; 
} 

Both methods generate a warning about unreachable code!

The strange thing about the C# compiler is that if the unreachable code consists entirely of throw statements, then no warning will be issued about the unreachabiliy.

ADDITION: This Stack Overflow question is related

like image 25
Jeppe Stig Nielsen Avatar answered Oct 04 '22 03:10

Jeppe Stig Nielsen