Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C# 4.0

Best Practices on Using Implicitly Typed (i.e. var ) and Explicitly Typed Variables

Rate me:
Please Sign up or sign in to vote.
2.68/5 (14 votes)
4 Nov 2009CPOL1 min read 81.9K   5   60
Best practise using var

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:

C#
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); //version of ‘Add’ method is not evident
}

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’.

  1. Do use ‘var’ to:
    1. Refer anonymous types, e.g.
      C#
      var anonymousType = new { Name = "Dilbert" };
    2. Refer query expressions, e.g.
      C#
      var queryExpression = from c in customers where c.Name == "Dilbert" select c;
    3. Refer complex generic types, e.g.
      C#
      var searchList = new Dictionary<string>();
  2. Do not use ‘var’ to:
    1. Refer known types, e.g.

      C#
      var customer = new Customer(); //Do not use 
      var numberList = new int[] { 1, 2, 3, 4, 5 }; //Do not use.
    2. Refer constants, e.g.

      C#
      var i = 5; //Do not use
    3. Refer simple expression assignments, e.g.

      C#
      var count = customers.Count();//Do not use
      var customerName = customer.Name;//Do not use
    4. Refer variables where types cannot be inferred or where inferred type is not what is intended, e.g.

      C#
      IList<customer> customers = new List<customer />(); //Do not use

      Consider code readability and maintainability while making a choice between ‘var’ and explicit type.

History

  • 4th November, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
PCoffey5-Nov-09 3:18
PCoffey5-Nov-09 3:18 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
ATANU.PODDER5-Nov-09 3:57
ATANU.PODDER5-Nov-09 3:57 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
Paulo Zemek5-Nov-09 5:45
mvaPaulo Zemek5-Nov-09 5:45 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
ATANU.PODDER6-Nov-09 2:22
ATANU.PODDER6-Nov-09 2:22 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
Paulo Zemek6-Nov-09 10:51
mvaPaulo Zemek6-Nov-09 10:51 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
ATANU.PODDER7-Nov-09 5:27
ATANU.PODDER7-Nov-09 5:27 
GeneralRe: Implicit and Explicit Variables do not perform differently!! [modified] Pin
Paulo Zemek7-Nov-09 15:16
mvaPaulo Zemek7-Nov-09 15:16 
GeneralRe: Implicit and Explicit Variables do not perform differently!! Pin
ATANU.PODDER8-Nov-09 23:18
ATANU.PODDER8-Nov-09 23:18 
Paulo Zemek wrote:
But, to be honest, I always though such feature must work in the reverse way. Instead of
var class = new Class()
I always though of something like:

Class class = new();
So, when the "type" is missing, the new will be automatically "Class". But, of course, this will help solve this discussion, but will not allow for unnamed types to be created.


Agreed.
GeneralThe basic message... Pin
Alexander Müller4-Nov-09 3:54
Alexander Müller4-Nov-09 3:54 
GeneralRe: The basic message... Pin
dequadin4-Nov-09 6:20
dequadin4-Nov-09 6:20 
GeneralRe: The basic message... Pin
Alexander Müller4-Nov-09 8:56
Alexander Müller4-Nov-09 8:56 
GeneralPlease follow the logic! Pin
Sergey Alexandrovich Kryukov9-Nov-09 5:35
mvaSergey Alexandrovich Kryukov9-Nov-09 5:35 
GeneralRe: The basic message... [modified] Pin
ATANU.PODDER4-Nov-09 20:40
ATANU.PODDER4-Nov-09 20:40 
GeneralRe: The basic message... Pin
Alexander Müller4-Nov-09 22:13
Alexander Müller4-Nov-09 22:13 
GeneralRe: The basic message... Pin
ATANU.PODDER4-Nov-09 23:00
ATANU.PODDER4-Nov-09 23:00 
GeneralRe: The basic message... Pin
Alexander Müller4-Nov-09 23:16
Alexander Müller4-Nov-09 23:16 
GeneralRe: The basic message... Pin
ATANU.PODDER4-Nov-09 23:56
ATANU.PODDER4-Nov-09 23:56 
GeneralRe: The basic message... Pin
Alexander Müller5-Nov-09 0:49
Alexander Müller5-Nov-09 0:49 
GeneralRe: The basic message... Pin
ATANU.PODDER5-Nov-09 1:08
ATANU.PODDER5-Nov-09 1:08 
GeneralBoxing and implicit typing. Pin
dequadin4-Nov-09 3:30
dequadin4-Nov-09 3:30 
GeneralRe: Boxing and implicit typing. [modified] Pin
ATANU.PODDER4-Nov-09 21:01
ATANU.PODDER4-Nov-09 21:01 
GeneralRe: Boxing and implicit typing. [modified] Pin
dequadin5-Nov-09 2:39
dequadin5-Nov-09 2:39 
GeneralRe: Boxing and implicit typing. Pin
ATANU.PODDER5-Nov-09 3:10
ATANU.PODDER5-Nov-09 3:10 
GeneralRe: Boxing and implicit typing. [modified] Pin
dequadin5-Nov-09 8:30
dequadin5-Nov-09 8:30 
GeneralRe: Boxing and implicit typing. Pin
ATANU.PODDER6-Nov-09 2:33
ATANU.PODDER6-Nov-09 2:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.