C # VS.NET 2010 constant expression evaluation

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 save the expression 10/2 == 5, vs .net will automatically generate a warning “Inaccessible code detected”.

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

Edited: Sorry for the incomplete question. Does this happen instantly and happen even before the code is compiled?

I supported each of the answers and accepted the first answer based on FIFO

+5
source share
7 answers

, 10 / 2 == 5 , . true, if . false, if .

, :

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

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

!

# , throw, unreachabily.

:

+4
if (10/2 == 5)

true,

throw new Exception();

,

return 0;

+9

, :

public int Test()
{
     throw new Exception();
}

, , , 10/2 10/2, 5... , , 5 == 5 . , , . - , , .

, , , , if true, if - return ( throw), , , , . , .

, , 10/2 == 6, "" 5 == 6, false. if , if:

public int Test()
{
    int num = 0;
    return num;
}
+4

,

return 0;

. 10/2 5.

+3

10/2 == 5, true, , return 0 .

10/2 == 6 false, return 0 , .

: , , . , , 10/2 == 5 , , , .

+2

( ) , 0 . , 10/2 == 5 . ,

if (10/2 == 5)

if true

, , , .

+1

, return 0

It simply warns that all code below 10/2 == 5 will never be interpreted as 10/2 will always be 5.

Similar:

if (true)
{
     ......
}
else 
{
  .....
}
+1
source

All Articles