Click here to Skip to main content
12,948,566 members (65,564 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


5 bookmarked
Posted 4 Nov 2009

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

, 4 Nov 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Best practise using var


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

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

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

      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.

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

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


  • 4th November, 2009: Initial post


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


About the Author

No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 1 Pin
ChantiPDM14-Jan-11 5:05
memberChantiPDM14-Jan-11 5:05 
GeneralMy vote of 1 Pin
Richard Deeming12-Nov-09 9:00
memberRichard Deeming12-Nov-09 9:00 
General[My vote of 1] Мethodically, socially and morally incorrect Pin
SAKryukov9-Nov-09 6:51
memberSAKryukov9-Nov-09 6:51 
Another effective argument it to ask suddenly: “Can I see your passport?”
M. Zhvanetsky

The whole article is methodically, socially and morally incorrect.
The general intention is maybe quite good: there are many techniques and features around which could be abused, some others are actually abused very often, so anyone could use a good advice on “Do” vs. “Don’t” -- only if the advice is good.

Actually, I disagree with most of the author’s statements; for others, I can see they are pointless. But this is not a real problem. The real problem is that those statements are just claims, with not a single reasonable word said to proof or just motivate anything.
What would make the author thinking he has an authority to claim all this with no motivation?
The whole reason I even pay attention for this article is that I would like to warn the beginners from using such baseless statements in their practice. Anything needs to be proven.

The discussion part is much worse.
Author just provokes the readers, so it looks like we catch his lure and try to argue with someone who does not accept most basic principles of argumentation.

Author’s manners not just bad; they are simply anti-social. This is nothing wrong of being aggressive in the argumentation. The only problem is being correct.

The author accuses the opponents on the base of irrelevant matters shifting the focus from his own mistakes.
One accusation sounds “as if they are on a mission to make such comments”. Why, on what grounds? It looks like an accusation in espionage, isn’t it?
I can imagine the amount of hate I can receive for this comment.

Another baseless accusation assumes the voters fail to understand deep thoughts of the author. “Not getting spirit of the article”, he says, huh? Considering the fact all author's claims are as simple as a brick, this kind of playing "understanding" card looks quite offensive.

How about this one:
“The posters were actually, I felt, not getting spirit of the article, getting stuck 2 just 2 lines of the whole article.”
How it sounds? Like this:
“You were only 2 minutes late for you train but cry as if you were whole hour late.”

Finally, for the very first time I need to force myself to address directly to the author:
Do you understand that with this publication of you article and especially discussion you virtually excluded yourself from this community?
I can hardly imagine many readers considering you seriously after all this.

Sergey A Kryukov

GeneralSuch an overreaction... Pin
CurtainDog9-Nov-09 19:45
memberCurtainDog9-Nov-09 19:45 
GeneralRe: Such an overreaction... Pin
SAKryukov10-Nov-09 5:43
memberSAKryukov10-Nov-09 5:43 
GeneralMy vote of 1 Pin
brian_agnes9-Nov-09 6:04
memberbrian_agnes9-Nov-09 6:04 
GeneralShould be based on facts and reasoning Pin
SAKryukov9-Nov-09 6:36
memberSAKryukov9-Nov-09 6:36 
GeneralMy vote of 2 Pin
Ben Robbins8-Nov-09 21:48
memberBen Robbins8-Nov-09 21:48 
GeneralRe: My vote of 2 [modified] Pin
ATANU.PODDER8-Nov-09 23:15
memberATANU.PODDER8-Nov-09 23:15 
GeneralMy vote of 2 Pin
dequadin7-Nov-09 6:52
memberdequadin7-Nov-09 6:52 
GeneralRe: My vote of 2 Pin
ATANU.PODDER8-Nov-09 23:27
memberATANU.PODDER8-Nov-09 23:27 
GeneralI understand the boxing reference Pin
Member 36807856-Nov-09 5:09
memberMember 36807856-Nov-09 5:09 
GeneralRe: I understand the boxing reference Pin
dberindei8-Nov-09 22:24
memberdberindei8-Nov-09 22:24 
GeneralRe: I understand the boxing reference Pin
Member 36807859-Nov-09 6:36
memberMember 36807859-Nov-09 6:36 
GeneralRe: I understand the boxing reference Pin
dberindei9-Nov-09 21:23
memberdberindei9-Nov-09 21:23 
GeneralRe: I understand the boxing reference [modified] Pin
Member 368078511-Nov-09 7:45
memberMember 368078511-Nov-09 7:45 
GeneralRe: I understand the boxing reference Pin
dberindei11-Nov-09 23:04
memberdberindei11-Nov-09 23:04 
GeneralRe: I understand the boxing reference Pin
Indrora23-Nov-09 16:10
memberIndrora23-Nov-09 16:10 
GeneralRe: I understand the boxing reference Pin
dberindei23-Nov-09 21:42
memberdberindei23-Nov-09 21:42 
GeneralRe: I understand the boxing reference Pin
Indrora4-Dec-09 16:12
memberIndrora4-Dec-09 16:12 
GeneralRe: I understand the boxing reference Pin
dberindei9-Dec-09 2:17
memberdberindei9-Dec-09 2:17 
GeneralWhy comparing "object" with "var"? Pin
SAKryukov9-Nov-09 6:33
memberSAKryukov9-Nov-09 6:33 
GeneralRe: Why comparing "object" with "var"? Pin
Member 368078511-Nov-09 9:39
memberMember 368078511-Nov-09 9:39 
GeneralRe: Why comparing "object" with "var"? Pin
SAKryukov11-Nov-09 12:14
memberSAKryukov11-Nov-09 12:14 
GeneralMy vote of 2 Pin
Utwig6-Nov-09 2:58
memberUtwig6-Nov-09 2:58 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170524.1 | Last Updated 4 Nov 2009
Article Copyright 2009 by ATANU.PODDER
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid