简体   繁体   中英

Why “var” keyword sets to certain type?

Why var a = 7; would set a type to a certain type (ie int instead of byte )? Are there any rules/defaults/checks made on the fly by C# compiler?

It's not clear what you mean by "on the fly" - but the C# compiler simply follows the rules laid down in the spec. For a declaration of the kind:

var a = expression;

the type of a is the type of expression . The expression 7 is of type int , although it's also known to be a constant within the range of byte , allowing:

byte a = 7;

to compile. The availability of that conversion to byte doesn't change the type of the expression 7 though, so int is what the C# compiler uses for the type of a .

Note that I'd recommend against using var for constants like this. It ends up with code which can get pretty confusing around the boundaries of int , uint , long etc. var is meant to help with anonymous types, and also to help make code more readable. When it makes code less readable, just don't use it.

The compiler treats any integer literal in your code, that does not have a suffix, as an int .

So this:

byte myByte = 255;

..is actually implicitly converting the int constant 255, to a byte.

That is why var is infered to be an integer.. because the compiler uses integer literals by default.

If you were to do this:

var a = 7L;

A would be of type long .

There are defaults, I couldnt' tell you all of them off hand. Similar to if you call 5/7 that it defaults to integer division. but if you do 5/7.0 then it will do regular division. var just sets the type to be whatever is the type of the assigned value, in your case without a cast it is an integer by default.

var does not mean "determine the type at runtime", it means "determine the type using the result type of the expression on the right hand side of the assignment operator." It is determined at compile time.

Per the manual :

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

and :

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

In plain and simple terms, the compiler will check the lowest available type for the data assigned to the variable and will strongly-type said variable to that data-type.

The var keyword automatically sets the giving value to the type that the compiler can convert. Ex: var s = ""; contains a string and will be made a string.

它将a设置为表达式类型,因为var是一般类型,因为CLR为您处理所需的内存管理,并将确定表达式的类型并使变量成为该类型。

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