Back to C# Language Enhancements.Implicitly typed local variable allows variables to be declared without having to specify the .NET type at design-time. The strong-type assigned to the variable is inferred at compile-time from the initialization expression.
In general terms it allows us to change:
int n = 5;
string s = “LINQ rules”;
int[] nums = new int[] {1, 2, 3};
To:
var n = 5;
var s = “LINQ rules”;
var nums = new int[] {1, 2, 3};
There variable n in both cases is defined as a strongly typed integer, and variable s is defined as a string. Unlike its similarly named var keyword in some other languages where it described a loosely-typed variant value, the var keyword simply strongly-types a variable instance to the type of the initialization statement.
There are a couple of important restrictions when using the var keyword:
- The declaration must have an initializer that the compiler can resolve to a type definition.
- The initializer expression cannot evaluate to null. The compiler must be able to determine the type.
- A type called var cannot be in the same scope, otherwise it is used.
- The var keyword must only be used for local variable declaration.
You can also utilize explicitly typed local variables in a for or foreach statement:
int[] nums = {1, 2, 3 };
foreach ( var n in nums ) {
}
for ( var n = 0; n < nums.Length; n++ ) {
}
This feature seems pretty basic to begin with; nothing more than a superfluous syntax addition for lazy programmers. It is not until you begin writing LINQ queries that its importance to the viability and usability of LINQ is evident. Eg. It is the only way to assign an
Anonymous Type. To maintain good code readability it is important that you restrict use of the var keyword to Anonymous Types. Using var in other places doesn't give you any advantages and makes it harder for a reader to determine the type of object they are dealing with.
EditReferences
Google search: Implicitly Types Local Variables C#