Introduction
Leveraging the type inference is wonderful when writing code. With the arrival of ‘var
’ in C# 3.0, it now allows a developer to write more relaxed code.
int i = 2
can now be written as var i = 2
, without having to worry about the overhead for boxing/un-boxing.
The compiler infers the type indicated by ‘var
’ from the expression used to initialize the variable, and the IL code contains the inferred type. However, it is not always the best thing to use var
. While using ‘var
’ can help developers to avoid all the type declarations for local variables, it has an impact on code readability. Consider invoking an overloaded method, which differs in the parameter type. If the method is invoked with parameters declared as ‘var
’, it makes the code complex to understand.
Consider the following snippet:
private int GetUserInput()
{
Random r = new Random(1);
return r.Next();
}
private int Add(int numberOne, int numberTwo)
{
return numberOne + numberTwo;
}
private float Add(float numberOne, float numberTwo)
{
return Convert.ToInt32(numberOne + numberTwo);
}
private void InvokeAdd()
{
var numberOne = GetUserInput();
var numberTwo = GetUserInput();
var addedNumber = Add(numberOne, numberTwo); }
Which version of ‘Add
’ method is invoked is not evident at the first glance, in the above snippet.
Although the best practices for using ‘var
’ cannot be made generic but a little guidance can help in making a conscious choice. Below are a few thoughts on when to use or not to use ‘var
’.
- Do use ‘
var
’ to:
- Refer anonymous types, e.g.
var anonymousType = new { Name = "Dilbert" };
- Refer query expressions, e.g.
var queryExpression = from c in customers where c.Name == "Dilbert" select c;
- Refer complex generic types, e.g.
var searchList = new Dictionary<string>();
- Do not use ‘
var
’ to:
-
Refer known types, e.g.
var customer = new Customer(); var numberList = new int[] { 1, 2, 3, 4, 5 };
-
Refer constants, e.g.
var i = 5;
-
Refer simple expression assignments, e.g.
var count = customers.Count();var customerName = customer.Name;
-
Refer variables where types cannot be inferred or where inferred type is not what is intended, e.g.
IList<customer> customers = new List();
Consider code readability and maintainability while making a choice between ‘var
’ and explicit type.
History
- 4th November, 2009: Initial post