When to Use and Not Use var in C#

Many languages, particularly scripting languages, have a loosely typed variable type named var. In these languages, var can hold any type of data. If you place a number into a var then it will be interpreted as a number whenever possible. If you enter text it will be interpreted as a string, etc. ‘var’s can even hold various objects and will behave properly.

As you probably already know, C# has supported the variable type var since version 3.0. Ever since, the debate has raged on: you should always use var; you should never use var. There are arguments for both sides that sound good, as we’ll see below. What I will say is that it depends. I propose that there are places to use var and places not to use var.

One important point to remember with C#, however, is that var is strongly typed. Once a var is declared it can only be of the type with which it was initialized. And a var must be initialized in order to be declared.

Some Arguments For var

  • var requires less typing. var is shorter and easier to read, for instance, than Dictionary<int,IList<string>>.
  • var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it’s used.
  • var encourages you to use a descriptive name for the variable. This means the instance, not the type name. For instance:
    • var customer = new Customer() rather than var c = new Customer().

Some Arguments Against var

  • var obscures the actual variable type. If the initializer doesn’t return a clearly defined type then you may not be able to tell the variable’s type.
  • Using var is lazy. While var is certainly easier to type than Dictionary<int,IList<string>>, if the variable isn’t named well, you’d never know what it refers to.
  • Using var makes it hard to know what type the underlying variable actually is. Again, a properly named variable speaks for itself.
  • var can’t contain nullable types such as int?. This is actually untrue as you can cast a value to a nullable type
    • var nullableInt = (int?)null;

How I Use var and Suggest You Do As Well

Although I agree with some of the arguments above, I have fairly specific rules that I use to determine whether I will use var or specify the type literally.

I use var any time that the initialization of the variable clearly tells me what the variable will contain.

var count = 17;
var primeNumbers = new [] { 1, 3, 5, 7, 11, 13, 17 };
var customer = new Customer();
var activeOrders = GetAllOrders().Where(o => o.Active);
foreach (var activeOrder in activeOrders) { … }

Note that in all of these cases, the variable names are descriptive and the initializer is clear. I also pluralize enumerations and arrays.

Cases where I do not use var, even though I still name the variable descriptively, are when the initializer is not clear.

decimal customerBalance = GetCustomerBalance();
CustomerStatus customerStatus = GetCustomerStatus();

I declare customerBalance as decimal to know its type for clarity. Reasonable alternatives might include double or even int or long. The point is, I don’t know by looking at the code.

I declare customerStatus as the Enum that it is. This makes it clear there are a limited number of possible values that can be referenced or tested by name.

Michael Brennan, in his blog post Why You Should Always Use the ‘var’ Keyword in C#, makes some compelling points. I recommend it for further reading. However, I prefer the clarity of specifying otherwise obscure types just to make things as clear as possible to the reader who may have to maintain my code in the future.

Join the Conversation

  1. Tom Faust


Your email address will not be published. Required fields are marked *

  1. I have been professionally programming since 1997, and leading programming teams for 20 years. I can tell you that in ANY case where you aren’t absolutely forced to go with a var, it is worth it to spend the effort to strictly declare. When someone comes behind you to read the code, the curve to learn your code, and the likelihood to make an errant assumption are both greatly reduced with strict typing. I can tell you this, I love coding JavaScript in TypeScript for this reason. Untyped variables and code are just way too easy to mess up and introduce random, and sometimes quite capricious, errors. No one on my team would be allowed to code with variants like that. The up-front time save of a few keystrokes is definitely not worth it in the long-run. Also, I think that if you are not sure what the function you are calling, or the object you are constructing is going to return you shouldn’t call it until you have figured it out. Strict typing ensures the programmer knew exactly what was going to happen when they typed it. I will say this though: I use vars when I am sandbox coding. It is faster and often you are totally fine with trial and error there. But when I am ready to take some code from the sandbox into an actual permanent program, I convert all the vars strict object types.

    1. Thank you for your input. You mentioned TypeScript (which I also prefer to straight JavaScript). Just as with TypeScript, all C# variables are strictly typed (unless one uses object or dynamic). For instance, bool isActive = false; and var isActive = false; are functionally identical. Both are strictly typed. But of course, you are welcome to use or not use var however you like and however you feel is best for your team.

      1. Makes sense to use var when type is clear or inferred. isActive can be inferred that it is boolean and not confusing. However, a variable named Status doesn’t infer anything and using var Status can lead to the next developer spending time figuring out if Status is string, enum or an something else.

  2. Some issues I have with var:
    1. If var represents a class, you can’t F12 on a var to see the class declaration.
    2. Even for simple types, something like “var number = 12” is unclear and potentially wasteful. Using var will make it an int, but depending on its usage, that could be a short, or ushort. It encourages wasteful programming, or worse, an unexpected overflow. It’s better to think about what type you really want each variable to be.
    3. Code is much more readable with explicit types.
    4. If you change the return value of a function, I want to know everywhere it was used. That var does not give you compile errors means you can miss things and get unexpected behaviour, particularly when marshalling for interop code.

    There is only one instance when I use var, and that is for an anonymous type.

    1. Also, another annoying aspect of var is when you are doing code reviews. Since you don’t have access to the IDE while comparing it can be hard to tell exactly what is going on if things aren’t explicitly typed.

    2. Totally agree on this point. Hence I’d rather strongly type and appropriately name variables and use refactoring to rename a variable if needed. Have we forgotten refactoring??

      “4. If you change the return value of a function, I want to know everywhere it was used. That var does not give you compile errors means you can miss things and get unexpected behaviour, particularly when marshalling for interop code.”

  3. Hi there, great article. But I have to say I’m more of the old school method and everything must be typed out. I am coming from C++ and heck I think auto is evil so this is why… I’m probably gonna get flamed for saying this but that’s how I feel.

    1. I totally understand old school. I come from a C background. Every C# feature has a place and a reason. Part of the beauty of the language is its flexibility. And you won’t find any flames here.

  4. In one line you use it for int and few lines lower you state that you don’t want to use it in an int.

    var activeOrders = GetAllOrders().Where(o => o.Active);
    foreach (var activeOrder in activeOrders) { … }

    I tend to use the .ToList() function and explicitly declare the active orders, but I definitely would have declared the activeOrder in the for if I didn’t do the first.
    I wonder if that is a:
    * table structure of the order headers
    * a specific query structure that only have the id, reference, debtor name and total value in it
    * a structure that has the header and all line items in it
    * a structure that has header, line items and discounts etc.
    * a wrapper class that contains the previous mentioned structure but have some of the header variables as properties.

    That is why I like to see an explicit type when something is declared. It just let me know which functions can use that as is, or how it will have to be wrapped to be used.

    1. You are always free to use the explicit declaration if you prefer. But that wouldn’t help you know if it contains line items and such. If those potential line items aren’t referenced in your foreach loop then you probably don’t care, but more to the point, the query should not do any more work than necessary if you can control it.

      On another note, you say you like to use .ToList() on your query. There are times this makes sense, such as to prevent multiple enumeration. However, consider the possibility that the table from which the active orders are retrieved may contain millions of rows. Doing .ToList() will attempt to read all of that into memory and would likely fail. I’m just saying to be aware of the size of the data set when using it. Processing without the list takes only what is necessary as you need it (possibly with some buffered rows to lessen database access, but not all of them).

  5. I absolutely agree with your rule of thumb for when not to use ‘var’. It’s nice to see that other engineers share the rule of using the type over var when the returned type isn’t clear. Sure, I can hover over the method in my IDE, but sometimes using the type adds clarity immediately without that additional step.

  6. The problem with rules like this (use var when this, don’t use var when that), is that it quickly gets sloppy and the lines become blurry. You also waste time trying to comply with yet another rule. At least when everything is typed you know what you have to do and you keep things simple.

    1. Thank you for your comment. This article is indeed my opinion; how I (and my team) like to write code. I don’t know that I’d call it “rules” as much as how we limit verbosity while maintaining clarity in our code. Of course you should do what you feel is best for your project and team.

  7. When it says
    “You only have to change the method call, not every place it’s used.”
    I guess you meant
    “You only have to change the method declaration”.

  8. If you have:
    var bar = foo.GetBar(); // returns an IBar

    Why do you care what type foo.GetBar() returns? We can see right in the code that bar can DoABarThing() without needing to explicitly state that bar is an IBar. I can count on zero fingers the number of times that an explicitly stated type was helpful for me in reading and understanding someone else’s code.

    1. I appreciate your comment. To answer your question, I care because I prefer visual clarity, even if technically Visual Studio and the compiler will make sure var always works. We all have our preferences. Mine is as I describe here. But I also understand that others have different opinions, which is why I also referenced Michael Brennan’s article. I would assume you agree more with his reasons than mine and that’s okay with me.

    1. Good question. No, there is never a case where you absolutely have to use var. Var is compiler magic introduced in C# 3.0 that compiles to exactly the same IL as if you had specified the variable type literally. But it does help, for instance, in the case where you ‘select new { cust.Name, cust.Phone }’ in a Linq expression, by not requiring you to create a class to receive the results. Var handles this for you automatically within the compiler. (See more here)

        1. I stand corrected. Thank you DaTurk. An anonymous object does indeed require a var. For example, the following object could not be held in a variable without using var.

          var anon = new
          Name = "Enigo Montoya",
          FavoriteNumber = 42

      1. This works:
        public static void Main()
        long num = 17;
        num = 9223372036854775800;

        This does not:
        public static void Main()
        var num = 17;
        num = 9223372036854775800;

        It is because the compiler has assumed (because of the missing ‘L’) that the number will not be used as a long later.

        Adding a type to the variable declaration has cleared up all ambiguity here. Specifying a type is always the clearest approach. As developers we should always make our code as clear as possible.

        [This of-course is a very simple example, in practice the situation would be more complex.]

        1. Thank you for reading my blog! I use var when it’s clear and obvious, which is usually the case in small sections of code such as loops and short methods. When in doubt, be clear and give the full declaration.