Click here to Skip to main content
15,902,938 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 83.2K   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: I understand the boxing reference Pin
dberindei9-Dec-09 2:17
dberindei9-Dec-09 2:17 
GeneralWhy comparing "object" with "var"? Pin
Sergey Alexandrovich Kryukov9-Nov-09 6:33
mvaSergey Alexandrovich Kryukov9-Nov-09 6:33 
GeneralRe: Why comparing "object" with "var"? Pin
Member 368078511-Nov-09 9:39
Member 368078511-Nov-09 9:39 
GeneralRe: Why comparing "object" with "var"? Pin
Sergey Alexandrovich Kryukov11-Nov-09 12:14
mvaSergey Alexandrovich Kryukov11-Nov-09 12:14 
GeneralMy vote of 2 Pin
Utwig6-Nov-09 2:58
Utwig6-Nov-09 2:58 
GeneralRe: My vote of 2 Pin
ATANU.PODDER7-Nov-09 5:58
ATANU.PODDER7-Nov-09 5:58 
GeneralI would agree if you used correct argumentation Pin
Sergey Alexandrovich Kryukov9-Nov-09 5:44
mvaSergey Alexandrovich Kryukov9-Nov-09 5:44 
GeneralImplicit and Explicit Variables do not perform differently!! PinPopular
PCoffey4-Nov-09 8:04
PCoffey4-Nov-09 8:04 
The implicitly typed 'var' is just a compiler trick that makes life easier for us developers. C# 3.0 was released with no new CLR so nothing changed under the hood.

There has been some discussion around
int i = 2; vs. var i = 2;

they are the same thing.

here is some code that i slaved over for your consideration Smile | :)

private static void CreateImplicitInteger()
{
    var i = 2;
}

private static void CreateExplicitInteger()
{
    int i = 2;
}


the 2 methods produce the same IL:

.method private hidebysig static void  CreateImplicitInteger() cil managed
{
  // Code size       4 (0x4)
  .maxstack  1
  .locals init ([0] int32 i)
  IL_0000:  nop
  IL_0001:  ldc.i4.2
  IL_0002:  stloc.0
  IL_0003:  ret
} // end of method Program::CreateImplicitInteger


and

.method private hidebysig static void  CreateExplicitInteger() cil managed
{
  // Code size       4 (0x4)
  .maxstack  1
  .locals init ([0] int32 i)
  IL_0000:  nop
  IL_0001:  ldc.i4.2
  IL_0002:  stloc.0
  IL_0003:  ret
} // end of method Program::CreateExplicitInteger



Also, i would disagree with the author and encourage people to use var like so:
var customer = new Customer();

This can really save you time and effort when refactoring.
Let's say that i decide to create a CustomerBase class ot inherit form and then decide to new up my Customer as a CustomerBase.

If I use Implicit typing then I change my code in 1 place.
var customer = new Customer();

If I use Explicit typing then I change my code in 2 places.
Customer customer = new Customer();
GeneralRe: Implicit and Explicit Variables do not perform differently!! [modified] Pin
ATANU.PODDER4-Nov-09 20:24
ATANU.PODDER4-Nov-09 20:24 
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
Paulo 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
Paulo 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
Paulo 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 
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 

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.