Different types evaluated for the var keyword

I have the following 2 blocks of code that are designed to indicate the type assigned to the compiler with the var keyword.

 var b = 0x80000000 - 0x1; Console.WriteLine("b: {0}", b); Console.WriteLine("b.GetType()={0}", b.GetType()); uint val1 = 0x80000000; int val2 = 0x1; var c = val1 - val2; Console.WriteLine("c: {0}", c); Console.WriteLine("c.GetType(): {0}", c.GetType()); 

Conclusion:

  b: 2147483647 //Result of UInt32-Int32 //(as compiler assigns datatype in the //order of int, uint, long and ulong) b.GetType()=System.UInt32 //OK c: 2147483647 //Uint32-Int32 c.GetType(): System.Int64 //Not Understood, why not UInt32 ? 

If var b and var c have almost the same initialization where var c is even, then why does it give an unexpected System.Int64 data type?

+1
source share
3 answers

Because

var b = 0x80000000 - 0x1;

already calculated. Optimization

But

 var val1 = 0x80000000; var val2 = 0x1; var c = val1 - val2; 

Not yet calculated. and the compiler suggested that val1 and val2 could be changed later ...

 const uint val1 = 0x80000000; const int val2 = 0x1; var c = val1 - val2; 

c now UInt32 because the compiler computes it and knows what happens with the failure.

Because val1 and val2 are constant, and the compiler knows that they will not be changed. therefore no need for Int64

+3
source

The problem is that when you perform an operation between int and uint , uint converted to a signed number.

So that uint can store all its information (from 0 to 2 3 - 1) in an unsigned number, it must be sent to long (from -2 63 to 2 63 - 1), since the range of int is from -2 31 up to 2 31 - 1.

+1
source

The compiler automatically extends the type to 64 bits, as this is the only integer that can contain the result of the operation between UInt32 and Int32 . Try switching to

 ulong val1 = 0x80000000; long val2 = 0x1; 

and you will see a compilation error, because the compiler cannot find the type to store the result.

Int64 not an inferred type of b , because the compiler detects that the constants fall in the Int32 range. Try

 var b = 0x800000000000 - 0x1; 

and you will see the prospective type long

-1
source

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


All Articles