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

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

  3. 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”.

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