Implicitly Typed Local Variables

Posted by in C# category on for Intermediate level | Points: 250 | Views : 6939 red flag
Rating: 5 out of 5  
 1 vote(s)

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.

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Madhu Rokkam
Member Level: Bronze
Member Status: Member,MVP
Member Since: 1/13/2011 3:13:20 PM
Country: India
Thanks and Regards Madhu

Login to vote for this post.

Comments or Responses

Posted by: Vuyiswamb on: 2/20/2011 | Points: 25
Nice one thanks for the article
Posted by: Madhu.b.rokkam on: 2/21/2011 | Points: 25
thanks Vuyiswamb
Posted by: Tripati_tutu on: 2/21/2011 | Points: 25
Good article for new comers into this platform...
Posted by: Madhu.b.rokkam on: 2/21/2011 | Points: 25
Thanks tripati for your comments..
Posted by: Tripati.patro on: 2/21/2011 | Points: 25
Nice article which covers all kind of usage of "Var".

But only one thing missed is why a programmer will use Var keyword rather than original datatype ?
Posted by: Madhu.b.rokkam on: 2/21/2011 | Points: 25
Thanks tripati for your comments ...

Posted by: Venu_msis on: 2/22/2011 | Points: 25
Nice Article covers all Scenarios of 'Var'
Posted by: Madhu.b.rokkam on: 2/23/2011 | Points: 25
Thanks Venu...
Posted by: kr_prash-15912 on: 5/25/2012 | Points: 25
Great piece of information. Thank you!

Login to post response

Comment using Facebook(Author doesn't get notification)