Home  /  Questions  /  Question



69   95.7
Mar 17, 2011


Usage of the C# var keyword. Is there a Best Practice?

The C# var keyword was introduced in C# version 3.0.  According to Eric Lippert from the Microsoft C# team it was included for 2 primary reasons:

  1) To limit redundant code, such as: 

Dictionary<string, List<int, bool>> myDictionary = new Dictionary<string, List<int,bool>>();
and write is as

var myDictionary = new Dictionary<string, List<int,bool>>();

  2) To support anonymous types, which were necessary to implement LINQ, such as:

var car = new { Make = "Toyota", Model = "Camry" };
--

Now, much of the code you see floating around on the Internet coming from experts use vars just about anywhere where it can be used. However, I have developed a personal preference, i.e. best practice if you will, that goes like this: 

  • Value types, such as, int, bool, float, and string (as an exception) are explicity declared.
  • Reference types are declared with var.
Is there anything such as a 'C# var usage' Best Practice rulout there?




 



1,364   100.0
Mar 17, 2011
Some good points Henry.  You may be interested in this discussion as well.  And yes, anonymous types, that's pretty useful for jquery/json scenarios...

http://stackoverflow.com/questions/1205329/c-var-keyword-usage


 1 comment
 
In real estate it is all about location, location, location. In coding, it is all about readability, readability, readability. So, the best practice for using 'var' is to avoid it when it is going to degrade readability. - Use it when the type is obvious. - Use it when knowing the type is useless and doesn't affect readability or understandability. For example, loops are a perfect place to use 'var'. --- Saleh Najar  Apr 11, 2011