- Posted by Ian Suttle on July 23, 2007
- Filed under .NET 3.5
C# 3.0 introduces
implicitly typed local variables by way of the keyword “var”.
The use of var allows one to
assign a number of different types to a variable without explicitly stating
that variable’s type. Var is actually not a type at all, but
a keyword which instructs the compiler to infer the most appropriate type based
on the value or expression to the right of the equals sign. If you’ve developed
in the pre-.Net ASP languages you might be inclined to think of var as “Variant” - but don’t J. Forget everything you’d previously learned
about variant types as var is not even a loosely or late-bound type; it no
longer applies.
Let’s compare apples to apples here.
In C# 2.0 we would declare variables in a method in this
manner:
void MyMethod()
{
int x = 5;
string name = “ian”;
}
This type of declaration makes it quite obvious what a variable’s
type is, and the value it will contain.
Using var in C#
3.0:
void MyMethod()
{
var x = 5;
var name = “ian”;
}
As you can see above the use of var is indeed syntactically a bit faster, and offers a variable the
ability to receive an unknown (at design time) value type. You really get what you pay for however. Even though var has its place with LINQ, it would seem abuse of the keyword for
standard variable usage could lead to ambiguity when reading or supporting the
code. One major plus on this note, I
found if I assign var x = 5, VS knows it’s an int at design time. If I then change this to be var x = 5 * 1.2452, VS recognizes it as a double at design time. Quite impressive!
What are the constraints of using implicitly typed local
variables? Here’s a quick list:
- Must be declared within a method
- Cannot be passed as arguments to other methods
- Can be used in “for” initialization:
- for (var x = 0; x < myArray.Length; x++) …
- Can be used in “foreach” initialization:
- foreach (var item in myItems) …
- Can be used in a “using” statement:
- using (var cmd = db.GetStoredProcCommand("_usp_AccountDelete"))…
Lastly, C# 3.0 also provides for implicitly typed
arrays, and is a key player in LINQ utilization. More on that soon.