Saturday, March 24, 2012

Implicitly Typed Local Variables (C#)

While coding, at some point, you might want to be able to declare a variable without having to explicitly mention the type of this variable.
C# 3.0 allows this by introducing a keyword var.

Here's how you use it:

var i = 0;
var str = "some string";
 
The type of the variable is deduced by the statement at the right hand side. However, these variables are still not loosely typed. You can check this be assigning different type of values to the same variable. For e.g., the variable i above cannot later on be assigned a string value.

The code below;

var i = 0;
i = "some string";

would give a compile-time error ("Cannot implicitly convert type 'string' to 'int' ").

Though, the use of implicitly typed variables may not be understandable by just these examples, these are really helpful when you are using LINQ.

References:


No comments:

Post a Comment