简体   繁体   中英

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 .

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

It's not var that defaults to Int32 , is the integer literal you assign to it.

You can use the suffix L to signal that you are writing a Int64 numeric literal.

var is not defaulting to anything. Rather, var stands in place of the actual type of the expression that initializes the variable. The question, then, is why is 255 considered int ? The answer is that without a type hint (f, d, m, U, L, etc.) integer literals are considered to be one of int , uint , long , or ulong , depending on which is the smallest type that will fit the number.

Some examples:

var i = 255; // var is int
var ui = 4000000000; // var is uint
var l = 5000000000; // var is long
var ul = 9223372036854775808; // var is ulong

Why not? Int32 is used most often I believe. Other numeric types have its suffixes to be added to literal values. Int32 was chosen to be the one without suffix.

If you want var to be other type, use a suffix, ie

var number = 123f;

will be float . See here for more info about numeric literals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM