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
if (10/2 == 5)
Will always return true, which means
throw new Exception();
Will always be executed, and
return 0;
Will never be reached
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With