Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a number declared as an implicit type default to integer in C#?

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.

like image 729
Vamsi Avatar asked Dec 02 '22 02:12

Vamsi


1 Answers

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

like image 136
Justin Niessner Avatar answered Dec 04 '22 22:12

Justin Niessner