Example 1
var test = Byte.MaxValue;
Console.WriteLine(test + " : " + test.GetType().Name);
Result 255 : Byte
Example 2
var test = 255;
Console.WriteLine(test + " : " + test.GetType().Name);
Result 255 : Int32
Example 3
var test = 10;
Console.WriteLine(test + " : " + test.GetType().Name);
Result 10 : Int32
Example 4
var test = 255;
test = Int64.MaxValue;
Console.WriteLine(test + " : " + test.GetType().Name);
Result : Error :Cannot implicitly convert type long to int
My question is why does C# default the type to Int32 when using var
.
C# isn't defaulting to Int32 just when you use var. C# defaults to Int32 when you declare an integer literal without supplying a type hint (as long as the literal fits into an Int32, otherwise it will go to Int64). Since the literal is typed as Int32, the var automatically picks up that type:
In C#, literal values receive a type from the compiler. You can specify how a numeric literal should be typed by appending a letter to the end of the number. For example, to specify that the value 4.56 should be treated as a float, append an "f" or "F" after the number - MSDN
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