Impossible comparison between stall and long suddenly possible

I know why this is not allowed:

ulong x = 0xFEDCBA9876543210; long y = Int64.MaxValue; Console.WriteLine(x < y); 

Obviously, there is no way to implicitly use either an operand for another type or a larger type to perform the comparison.

The operator '<' cannot be applied to operands of type 'ulong' and 'long'.

So this is also invalid (with MinValue and const ):

 ulong x = 0xFEDCBA9876543210; const long y = Int64.MinValue; Console.WriteLine(x < y); 

However, this is allowed (instead of MaxValue ):

 ulong x = 0xFEDCBA9876543210; const long y = Int64.MaxValue; Console.WriteLine(x < y); 

There is no overload < accepting ulong and long , but I saw with Reflector that it silently converts Int64.MaxValue to ulong . But this does not always happen. How does it work and what considerations are the cause of this inconsistency?

+6
source share
2 answers

One big difference between long y = Int64.MaxValue; if (x < y)... long y = Int64.MaxValue; if (x < y)... and if (x < Int64.MaxValue) is that in the latter case, the compiler can actually see a constant value if it wanted to. He can see that the actual constant value matches the ulong range, and therefore the implicit listing is ok.

For a simple variable long y compiler cannot make any assumptions about what the run-time value y is. Nevermind that an assignment operator is just one statement; the compiler does not keep track of the values ​​assigned to the variables.

As DarkGray noted, const var behaves like a constant, since you told the compiler that its value would never change.

+3
source

Const long with a value in the ulong range silently converts to const ulong.

It is allowed:

 ulong x = 0xFEDCBA9876543210; const long y = Int64.MaxValue; Console.WriteLine(x < y); const ulong z = y; 
+1
source

Source: https://habr.com/ru/post/921438/


All Articles