Can the C# ‘var’ Keyword be Misused?

More and more often I've been seeing C# code like this:

var Data = GetData();

What on earth does GetData() return? This code is not as maintainable as it could be and is not as maintainable as it should be.

Doesn't explicitly declaring the variable type make the code more readable, understandable and ultimately more maintainable?

DataTable Data = GetData();

Ahhh, GetData() returns a DataTable.

I know that var has uses but I wish it would have been named something much longer because typing 'var' is too easy. Perhaps it should have been named AutomaticTypeVar or even AutoVar to reduce the lazy misuse.

Just my 2 cents.

Steve Wellens


A user on the Asp.Net forums was kind enough to provide this quote and link:

"However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required." 

 [Update 2]

This list shows a progression of  zero semantic information to the maximum semantic information:

var x = functionA();           // worst, no one should like this
var x = GetIndexes();          // better
var Indexes = GetIndexes();    // even better
int[] Indexes = GetIndexes();  // best, you don't need to guess at the type returned 




  • I fully agree with you here.
    I've seen alot of misuse of the var keyword in source code from co-workers.
    One of the first things i do when i get to work with that code is replacing all the "var" with the exact datatypes.

    The best thing to do, in my opinion, is to never use this keywords unless it is mandatory.


  • The GetData method name used in you example is worse than the use of var.

    If I couldn't get that method fixed, I would tend to declare the type.

  • >> The GetData method name used in you example is worse than the use of var.

    It is a contrived example to illustrate a point.

    In a real application I would not give a method such a bland meaningless name.

  • It is not Microsoft's fault that developerx choose to abuse useful and powerful tools. I think "var" is excellent. My rule of thumb is that if you do not know how to use it then limit usage to LINQ.

  • I couldn't disagree with you more.

    explicit typing is useful if you're writing apps in Notepad, but with an IDE that lets you hover and inspect, it's no more maintainable than var, ime.

    A well-named method buys you a lot more analyzability than explicit typing does, and using 'var' provides a lot more flexibility during refactoring and other code-maintenance tasks.

    And in the case of static code reviews, does it *really* matter whether GetCustomerOrderHistory() returns a DataTable or an IList, or whatever? More specifically, does it matter *in the context that var was used* or is that something you can cover when you are reviewing that actual method?

    again, ime, the answer is 'no'. You can logically follow the app's intent w/o the explicit typing.

  • Bad users will always misuse good tools, anyway.

    var dtUsers = GetUsers();

    Is that a misuse?

  • My 2 cents:

    First : If possible refactor the method name !
    Second : If useful, declare the type, but only if it's useful


  • >> In a real application I would not give a method such a bland meaningless name.

    And in such a case, the use of var might not be so bad.

    This is something that is useful but is easily subject to abuse. Those who are inclined to abuse it would not be discouraged by it having a longer name.

    I've seen people use it very badly: var helloMessage = "Hello World"; var terrible=true;

    I've also seen it simplify some complex refactoring where the type was unimportant within methods and because they used var, those methods did not need to be changed.

  • I don't agree with the author. If you can't understand what the intent of the code is by looking at the naming conventions, etc, you have a much bigger issue of code getting messier.

    I would say if you can't figure out what the code does from the variable names and function names, its time to refactor code until it starts becoming intuitive. 'var' helps a lot in this regard.

  • var sucks = true;

    Coders with poor refactoring skill/motivation will make code look like soup when given the chance to use var.

  • I'm surprised some would argue that the function name is important...the variable name is important...but the type name, why it doesn't matter at all!

    The more information you can convey with the code text, the more maintainable the code will be.

    Perhaps some are guilty of using lazy short-cuts and are trying to defend them. Shame on you! :)

  • I would say make your variable name more descriptive, that is much more valuable. That way everywhere you use the variable you can read what it means. Also the implementation is much less important then its intent.

  • So you're saying that the use of "var" in the example harms the code clarity more than the poor function and variable names? Sorry, not buying it.

  • >> So you're saying that the use of "var" in the >> example harms the code clarity more than the poor >> function and variable names? Sorry, not buying it.
    No, I am not saying that.
    I'm saying descriptive names improve maintainability.

  • I use the var keyword to reduce noise from my code, because most often, the variable type could be considered noise.

    As said above, using var should not change the readability of the code. The purpose by using a good variable name and the method name must be much clearer.

    Sometimes though, you don't want to use var. When you want to make clear that the variable is a base type of an interface.

    IPerson person = new SuperHero();

    But I love to use it in a foreach where it is just noise to print out the type of the item.

    foreach (var person in persons) { .. }

  • I agree with "paul.vencill" on this one. As long as you use any tool other then notepad (or similar) then why do you need to know what type you are actually using? Isn't the methods the important thing? Doesn't visual studio help you there?

    If you really need to know the datatype, then just name your variables and methods properly and it's all solved.

    Another common misunderstanding I see a lot is the one "Mikael Lundin" describes. IPerson person = new SuperHero();. How is that better then var person = new SuperHero();? You still have a dependency on the class SuperHero, thats a fact. So that will gain you exactly zero advantages. You can still use it in any method that takes a IPerson.

    I use var everywhere. And it gain me a few advantages, like easier refactoring, while it has no disadvantages.

    My answer to the question is: No, var can not be misused. If you need to declare the type to be able to read the code, you are doing something wrong.

  • >> var improves readability
    Sure it does and o and l make good variable names.
    It's surprising that some who use var where it's inappropriate would dedicate any energy to defending the lazy practise.  Maybe 'bad-code-guilt' is providing the impetus.  :)

  • Now step back and look at var in the light of dynamic languages...

  • The problem comes in when using black-box controls/libraries.

    If monkey A wrote a method GetUserList, and someone just used Var users = GetUserList(); that looks like poo. I'm sorry but it does. Writing List users = GetUserList(); doesn't take much time. The last thing I want is my code to look like some JavaScript flunky got lose in our office.

  • C# should have used var only when you can't explicitly give the type name.

    people who like var, the C# 4.0 dynamic or whatever, why not use some other language within the .net framework?

    why should c# take the middle ground of trying to please everyone and support all programming styles, wasn't the .net framework itself supposed to provide that flexibility?

  • Perfectly right! var is for kids. But the community has remembered well: the method must be meaningful.

  • All good points, just my 2 cents to follow. I hate var, I hate it with a passion - I hate the fact I have to use it for anonymous types, even! That aside, I had to have this discussion with colleauges who loved (and overused) it. Our working rule was:

    "If a human can't immediately infer the type, then the compiler shouldn't." So...

    var s = "hello, world!"; is OK (I still hate it...)
    var buidler = new StringBuilder(); is OK

    var data = GetData(); is NOT OK

    And this rule stands for us REGARDLESS of how well a method/property is named, to avoid subjectivity and arguments. Besides, things should be named well regardless, and var does not fix naming conventions.

  • MS .NET trainer here. var is all kinds of slop.

    I could write an app using all var declarations and then write another using full type names and I will take bets on which code base can be maintained with less man hours.

    Deep down inside you know it too.

    var SHOULD HAVE been restricted to only compiler generated types, now every wanna-be master guru programmer thinks it is hip to use it, the dumb ones just do it because they see the "herd" doing it.

    var keywords decrease the meaning of code, or the readability of code which increases the time it takes for devs to research.

    It is like using 'it' all the time because it is easier to use it. ;)

  • DougR, you hit the nail on the head - "it is just lazy, sloppy code".
    But "can't give me a specific, compelling reason of why they they used it then the person is not hired" - I'm not that bad, but I do insist the candidate at least be able to tell me what the type should be and why they didn't use it.

    As a developer for over 20 years, I have to say, the "var" keyword is very much over used.
    The statement "Just hover over the declaration" is plain and simple BS - and a perfect example of the "lazy" principle.
    When I am coding, my hands are over the keyboard and my eyes are directed at the monitor. I neither have the time, nor the inclination to take my hands away from the keyboard, find the mouse, find the mouse pointer (on a multi-monitor system), move the mouse to the variable and wait for the hover to tell me what the variable type is. MY EYES ARE ALREADY ON THE SCREEN. It takes me a hell of a lot less time to move them directly to the variable declaration.
    Even in longer methods where the variable declaration is off screen, it is a simple matter of "Go to declaration", "Go to Previous Location". Hmmm... There are keyboard short-cuts for that too! Once again, my hands have not left the keyboard.
    Yes, "var" is cool, and yes. sometimes "var" is necessary (when dealing with anonymous types for example), but how long does it take to write our a type declaration? Oh look! There's CTRL-space!
    Sometimes I think people need to go back and do CS-101 again (or at all for that matter).

Comments have been disabled for this content.