Using var (Implicitly Typed Local Variables) in your C# code.

26. August 2010

    Local variables can be given an implicit type of 'var' instead of explicit types. The compiler will resolve the type from the expression. Note that var can only be used when a local variable is declared and initialized in the same statement.

    I found some people discouraging the usage of 'var' in C# code and the reason that they are giving is that the var type makes the code more difficult to understand. It is not always true, using the var keyword should be discouraged in a places like the following code:

var data = GetData();

    When you read the above code, we will not know the type of the variable 'data'. This code is not understandable as it can be more it can be. If you change the above code like below, it makes the code more understandable.

DataTable data = GetData();

    'var' can be used in places like where below. <.p>

var data = new DataTable();

Here, the reader will not have any misunderstanding about the type of the variable ‘data’.

It makes sense to use var in teh following places.

  1. When creating anonymous types : var person = new { Name = "Name", Age = 25 };
  2. Object creation : var data = new DataTable();
  3. Cast expression: var data = (DataTable)obj; or var data = obj as DataTable;
  4. Generic method call or property with explicit type arguments, when return type is generic: var manager = serviceProvider.GetService<IManager>() or var manager = Singleton<Manager>.Instance;

.Net Tips, Technical, c# , ,

blog comments powered by Disqus