Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »

Implicitly Typed Local Variables

Modified: 2008/01/27 18:48 by t_magennis - Categorized as: Language
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.

Edit

References

Google search: Implicitly Types Local Variables C#

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or ommissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain un-intentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.