Monday, May 21, 2012

C# 'var' keyword versus explicitly defined variables

 If you explicitly define your variable like this:




List<MySuperEngine> lstString = new List<MySuperEngine>;


Resharper may make a suggestion to use var keyword. It helps for typing and readiblity of code. If it is not ambigous to use it, you can replace first part with var.



var lstString = new List<MySuperEngine>;





I know the type of the object, so it is obvious what we are referring to with "var" keyword. It is useful if the type name is too long to type it like

MyanotherClassWithNameSpace.ClassA obj = new MyanotherClassWithNameSpace.ClassA();


"var" keyword is not same as "dynamic" keyword. "var" is only place holder and it is for your convenience. It saves extra typing. You will have same IL code as explicit definition.



No comments:

Post a Comment

Hey!
Let me know what you think?