Implicitly Typed Local Variables

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This

This will give clear idea about this new feature introduced by Microsoft in C#3.5 language enhancements.

Local variables can be declared using var keyword instead of an any type. The var keyword lets the compiler know that the type of the variable is to be defined from the expression on the right side of it’s initialization.

Check the below samples

//x is compiled as integer
int x = 10;
var x = 10;

you can test this as below


// In Both the strArr is compiled as string array only.
string[] strArr = new string[] {“a”, “b”, “c”};
var strArr = new string {“a”, “b”, “c”};

You can test this as follows


//Similarly you can declare an anonymous type like this
var emp = new {Name="Madhu", Age=31};

Few important points to remember about the Implicitly typed local variables are

a) var is type safe.
b) var cannot be used at class level.

c) var cannot be assigned null during declaration;
var x = null; // this is a wrong statement and cannot be given.

d) var is used  in the methods locally. (i.e. local to any method)

e) var can be used in foreach statements.

foreach(var row in dataTable.rows)..
foreach(var item in somelist)..
f) You can initialize only one variable of var type in a statement.
var z = 10; //Can be used;
var a,b,c; //This cannot be given.

g) var cannot be used in method parameters.

h) var cannot be used as return type

Hope you all like this article. Do comment on this.