Implicit Typing - The C# var Keyword
Introduced with C# 3.0 (used in Visual Studio 2008, .NET 3.5 and later), the C# var keyword allows for the implicit typing of local variables.
For example, if I wanted to create a generic dictionary without implicit typing:
With implicit typing, I simply replace the variable type with the var keyword:
This simply instructs the C# compiler to figure out the type of the "parameters" variable based on what it is assigned to.
It's important to note that this does not imply a variant type or that "parameters" is not strongly typed. The two chunks of code above are equivalent, it's just that in the second one I'm letting the compiler do the work and saving myself some keystrokes.
Restrictions
Since the compiler is doing the work of determining the type of the variable being declared, it's not valid to use var without providing for the initialization of the variable:
Another restriction on using var are that it can only be used on local variables. Variables scoped at the class level cannot use var even if they are initialized when declared:
Purpose
The main purpose of the var keyword is to enable the use of anonymous types. Anonymous types are types whose definition is generated by the C# compiler - so you as the programmer don't have access to the name of the class! Therefore you can't create a variable to reference an instance of the class without using var. For example:
In this case I don't have to know the specific type returned by my query - and in this case I couldn't specify it anyway because the compiler is generating an anonymous type for me that holds CompanyName and ContactName. So I must use var in this case to refer to my result, and the compiler does the rest.
Guidelines
Use of var is always optional, unless you are dealing with anonymous types. But many developers are using it where they can to simplify and reduce the amount of code they have to write. The key here is to keep the readability of your code in mind. If usage of var in a situation introduces ambiguity to the code - don't use it in that situation!
- Ken
