The compiler reacts differently when assigning an int.MaxValue variable to a variable

According to the documentation int.MaxValue is an int field. When i do

int a = int.MaxValue;
int b = a + 1;

bmatters int.MinValueas expected. But when I do

int a = int.MaxValue + 1;

I get a compilation error

Operation overflows during compilation in validation mode

Why is there a difference?

+4
source share
3 answers

From https://msdn.microsoft.com/en-us/library/aa691319(v=vs.71).aspx :

A constant expression is an expression that can be fully evaluated at compile time.

and

, , .

, , ,

, , int a = int.MaxValue + 1; (int.MaxValue const int).

int a = int.MaxValue;
int b = a + 1;

, . (. , ). :-))

+2

, . int.MaxValue 1 . , .

, , , .

+2

, checked ( ), :

, , , , . , .

Since both int.MaxValueand 1are constant, you get an error.

If you use unchecked, you will see the same result

unchecked
{
    int a = int.MaxValue + 1; // a is int.MinValue
}
+1
source

All Articles