MSDN categorizes var under Types.
variables that are declared at method
scope can have an implicit type var
what does ‘implicit type var’ mean in this context?
Strictly said, if I have it to explain to fellow programmers.
Can I say; var is a Type, or do I have to say; var is a keyword that instructs the compiler to determine the type itself.
note: this is not meant to start a discussion about var, nor to learn the use of var. For once and for all I want to know excactly how to describe it and msdn is a bit confusing, that’s it.
varis a contextual keyword – along withyield,addandgetfor example.In other words, you can use it as an identifer without prefixing it with @, but it still has a special meaning to the compiler in some places (i.e. where a type name is expected for a local variable declaration).
Using
varto declare a local variable asks the compiler to infer the type of the variable based on the expression on the right hand side. For example:The type of
listisList<string>; the type ofanonis an anonymous type, also introduced in C# 3. Part of the reason for introducingvarin C# 3 was to allow for strongly typed variables using anonymous types – the variable still has the appropriate compile-time type, even though you couldn’t explicitly state that type.There are a few cases where
vardoesn’t work, however, if the compiler doesn’t have enough information:There are others too. In each case you could just cast the expression on the right-hand side, so that the compiler knew what to use – but in that case you might as well just declare the variable explicitly instead.
<plug>You can read more about this in C# in Depth. Fortunately, the chapter covering this is still available for free from the first edition page (you want chapter 8). I can’t remember how much I’ve changed this chapter in the second edition…
</plug>