Why You Should Always Use the ‘var’ Keyword in C#

iStock_000012751071XSmallUsing the ‘var’ keyword in C# has always spurred a hot debate among developers.  I believe ‘var’ should be used at all times.  I believe this not because I choose to be “lazy,” as those who argue against it frequently claim.  Of all the reasons I use ‘var’, laziness is not one of them.

I’ve argued for the constant use of ‘var’ countless times; this blog post is a collection of thoughts that I have compiled resulting from my arguments.  Below are my reasons for using ‘var’ all of the time.

It decreases code-coupling

Coupling between code and its dependent code can be reduced by using ‘var’.  I do not mean coupling from an architectural perspective nor at an IL-level (the type is inferred anyway), but simply at the code level.


Imagine there are 20 explicit type references spanning over twenty code files to  an object that returned an another object of type IFoo.  By explicit type references, I mean by prefacing each variable name with IFoo.  What happens if IFoo changes to IBar, but the interface’s methods are kept the same? 

Wouldn’t you have to change it in 20 distinct places?  Doesn’t this increase coupling?  If ‘var’ was used, would you have to change anything?  Now, one could argue that it is trivial to change IFoo to IBar in a tool like ReSharper and have all of the references changed automatically.  However, what if IFoo is outside of our control?  It could live outside the solution or it could be a third-party library.

It is completely redundant with any expression involving the "new" operator

Especially with generics:

ICalculator<GBPCurrency, GBPTaxType> calculator = new GBPCalculator<GBPCurrency, GBPTaxType>

can be shorted to:

var calculator = new GBPCalculator<GBPCurrency, GBPTaxType> 

Even if calculator is returned from a method (such as when implementing the repository pattern), if the method name is expressive enough it is obvious the object is a calculator.  The name of the variable should be expressive enough for you to know what the object it represents is.  This is important to realize:  the variable expresses not what type it represents, but what the instance of that type actually is.  An instance of a type is truly an object, and should be treated as such.

There is a distinction between an object and its type:  an object exists at runtime, it has properties and behaviors; types simply describe what an object should be.  Knowing what type an object should be simply adds more noise to the source code, distracting the coder from what an object really is.

An object may be brought into this world by following the rules governed by a type, but this is only secondary information.  What the object actually is and how it behaves is more important than its type.  When we use an object at runtime, we are dependent on its methods and properties, not its type.  These methods and properties are an object’s behaviors, and it is behaviors we are dependent upon.

The argument for knowing a variable's type has been brought up in the past.  The move from Hungarian notation in Microsoft-based C++ to non-Hungarian notation found in C# is a great example of this once hot topic.  Most Microsoft-based C++ developers at the time felt putting type identifiers in front of variable names was helpful, yet Microsoft published coding standards for C# that conflicted with these feelings.

It was a major culture change and mind-shift to get developers to accept non-Hungarian notation.  I was among those who thought that non-Hungarian variable naming was downright wicked heresy and anyone following such a practice must be lazy and did not care about their profession.   If knowing a variable’s type is so important, shouldn’t we then preface variable names in Hungarian style to know more information about an object's type?

You shouldn't have to care what the type of an object is

You should only care what you are trying do with an object, not what type an object may come from.  The methods you are attempting to call on an object are its object contract, not the type.  If variable names, methods, and properties are named appropriately, then the type is simply redundant.

In the previous example, the word "calculator" was repeated three times.  In that example, you only need to know that the instance of a type (the object) is a calculator, and it allows you to call a particular method or property.

The only reason a calculator object was created was so that other code could interact with its object contract.  Other code needs the calculator’s methods and properties to get something done.  This need has no dependency on any type, only on an object’s behaviors..

For example, as long as the object is a calculator, and the dependent code needs to call a method named “CalculateTax,” then the dependent code is coupled to an object with a method called “CalculateTax” and not a specific type.  This allows for much more flexibility, because now the variable can reference any type as long as that type supports the “CalculateTax” method.

‘var’ is less noisy than explicitly referencing the type

As programming languages evolve, we spend less time telling the compiler and the computer what to do and more time expressing problems that exist in the specific domain we are working in.

For example, there are a number of things in C++ that are very technical with respect to the machine, but have nothing to do with the domain.  If you are a customer of Quicken or Microsoft Money, all you really want to do is manage your finances better.  These software packages allow you to do that.

The better a software package can do this for you, the more valuable it is to you.  Therefore, from a development perspective value is defined by how well a software package solves a user's problem.  When we set out to develop such software, the only code that is valuable is the code that contributes to solving a particular user’s problem.  The rest of the code is unfortunately a necessary waste, but is required due to limitations of technology.

If we had infinite memory, we would not need to worry about deleting pointers in C++ or garbage collection in C#.  However, memory is a limitation and therefore the technician in us has to find ways of coping with this limitation.

The inclusion of ‘var’ into the C# language was done for a reason and bookmarks another iteration of C# (particularly C# 3.0).  It allows us to spend less time telling the compiler what to do and more time thinking about the problem we are trying to solve.

Often I hear dogma like "use var only when using anonymous types."  Why then should you use an anonymous type?  Under these conditions you usually do not have a choice, such as when assigning variables to the results of LINQ expressions.  Why do you not have a choice when using LINQ expressions?  It's because the expression is accomplishing something more functional and typing concerns are the least of your worries.

In the ideal C# world, we would not have to put any words in front of a variable name at all.  In fact, prefacing a variable with anything just confuses the developer even further, and allows for poor variable names to become a standard whereby everyone is reliant upon explicit type references.

Arguments against using ‘var’

Some of the arguments I have heard against using ‘var’ and my responses to these are:

  1. “It reduces clarity” – How?  By removing the noise in front of a variable name, your brain has only one thing to focus on:  the variable name.  It increases clarity.
  2. “It reduces readability and adds ambiguity” – This is similar to #1:  readability can be increased by removing words in front of the variable and by choosing appropriate variable names and method names.  Focusing on type distracts you from the real business problem you are trying to solve.
  3. “It litters the codebase” – This is usually an argument for consistency.  If your codebase uses explicit type references everywhere, then by all means do not use ‘var’.  Consistency is far more important.  Either change all explicit references in the codebase to ‘var’ or do not use ‘var’ at all.  This is a more general argument that applies to many more issues, such as naming conventions, physical organization policies, etc.


As a final thought, why do we preface interface names with “I” but not class names with “C” as we did in the days when Microsoft-C++ was the popular kid in school?

  1. gravatar

    # by Anonymous - September 24, 2010 at 11:20 PM

    Thanks. I've always been against using 'var', but you've made a compelling argument. I think I'm going to give it a try.

  2. gravatar

    # by Anonymous - September 25, 2010 at 5:29 AM

    let me know how it goes :)

  3. gravatar

    # by Anonymous - October 8, 2010 at 1:20 PM

    Make love not var ;-)

  4. gravatar

    # by Cody Wyers - November 5, 2010 at 11:36 AM

    nice. currently getting in trouble for refactoring code to use var.
    they say i'm var happy. i told them i'd stop as soon as the organization starts programming with notepad.

  5. gravatar

    # by Marcin - February 16, 2011 at 4:03 AM

    Thanks. Great post. I agree and really like the brevity of var. Sadly I have just bumped into a place that has a policy not to use var ever... you ideas will come handy if ever there is a discussion about it. Too often though these things are arbitrary and not agreed via a consensus.

  6. gravatar

    # by Unknown - July 2, 2015 at 3:23 AM

    This comment has been removed by the author.
  7. gravatar

    # by Q - August 22, 2015 at 9:53 PM

    I use var everywhere. I have a bit of a functional language background and it comes to me more naturally.

  8. gravatar

    # by Unknown - November 9, 2016 at 3:11 AM

    Quý khách có nhu cầu sử dụng đặt hàng Alibaba, Taobao và vận chuyển hàng trung quốc về Việt Nam. Quý khách cần chuyển hàng giá rẻ, nhanh chóng, uy tín. Hiện nay vận chuyển hàng Quảng Châu khá phổ biến với Việt Nam - Hà Nội, Quý khách có thể tham khảo qua bảng giá vận chuyển hàng tại đây. Chúng tôi hy vọng sẽ là đối tác đáng tin cậy, lâu dài của Quý khách. Sẵn sàng giải đáp mọi thắc mắc 1 cách nhanh chóng nhất.

  9. gravatar

    # by Anonymous - October 9, 2017 at 10:04 AM

    I work in codereview team and our programmers create very long pieces of code (hundreds lines per function). It is wrong, but there is a problem when you have 50 local variables in function and class variables with the same name as local variable. When we want to use var, this code is unreadable.

    I understand to use var but it is dependent on context of code. You can have a code where it is better to use var and where is better use strongly types.

  10. gravatar

    # by John - December 21, 2017 at 2:42 AM

    thanks for this article, especially for the comment at the end about I for interface. It seems like it should be something small, it's just an extra character. But, in an industry where eliciting precise requirements is meant to be one of the key skills it doesn't make sense that we can't apply that kind of critical thinking to our own practices

  11. gravatar

    # by Gusti - October 22, 2018 at 5:18 AM

    I'm using the explicit types because I am lazy. I don't want to infer the type from the name of the variable or from the method which is called. I don't want to mouse over in Visual Studio so that a tooltip with the actual type is shown. And code review in Azure Ops + var = sadness + disgust.
    I in interface? Because I (am a) Queryable, I (am a) Request, I (am a) Calculator? Like in I,Robot?

  12. gravatar

    # by Unknown - March 26, 2019 at 8:40 PM

    Thank you for the clear analysis :)

  13. gravatar

    # by Unknown - April 6, 2019 at 7:15 PM

    Have you ever worked with a strongly-typed language like C or C++? Have you worked with JavaScript *shudder*? Your arguments all, in fact, boil down to true laziness, no offense. IMO, 'var' is the worst thing to ever happen to C# and should *never* be used. As a responsible developer, I *need* to know that the object I'm working with is an IDictionary>(), or whatever. Any runtime binding errors will be a result of my laziness and will wake up some poor DevOps comrade at 3am, and they won't be found until the code is out in the wild. Not ok. That said, thanks very much for this post. I appreciate you even if I disagree. :) Cheers!

  14. gravatar

    # by Unknown - May 31, 2019 at 11:11 AM

    Maintainability & readability of code is much more important that these weak arguments of using var. Var simply obfuscates types. Thus "var" waste time and money of new developers who are unfamiliar with the code. It prevents new developers from coming up to speed on new code. Using var is like writing vague error messages. This was one of the reasons that it was left out when C# was first released. Only to placate the VB whiners was it added to C#. How about code converters. Ever converted VB with all the vars to a real early binding language. Perhaps you could argue that all functions should be Static and you should do away with objects. Perhaps VB Script and other interpreted languages is your preferred language. I would not want anyone to use it in mission critical code. Using var is sloppy, waste time and money. One of the Mars mission failed and crashed because the types did not match between the main applicaton and one of the dlls. One var was meters the other was feet what elevation to deploy the parachute. The radar module said deploy the parachute at 10,000 meters and the app read it as 10,000 feet. It impacted with a small crater. Robust mission critical software does not use late binding var. types. Early binding type errors are caught a compile time not at run time.

  15. gravatar

    # by Anonymous - July 29, 2019 at 2:31 AM

    #14 You fundamentally misunderstand var in c#. You cannot assign different types to the same var. In fact, the IL code emitted by the compiler does not include the concept of var. All it does is work out type the var should be based on the RHS expression.

    The Mars mission example is a different, and more insidious problem. When you declare "double parachuteDeployAltitude", what does it represent? meters? feet? km? miles? The type is not descriptive, nor is it restrictive. The compiler cannot help you. If you setup a custom type system and used "Distance parachuteDeployAltitude" then you avoid the problem. The key point is that now, using "var altitude = GetDeploymentAltitude()" will guarantee that you're working with the correct type. If you later try to use it as feet, instead of meters (maybe like "altitude.ToMiles()"), then the compiler will stop you unless your Distance class can convert Meters to Miles for you. Your examples are more to do with the problems of passing intrinsic types through interfaces than using var.

    Also, var was not introduced in response to demand from the VB community. It was introduced in C# 3.0 as Michael said. This was long after most people had migrated their VB6 projects to VB.Net. var was introduced to support LINQ. LINQ expressions return anonymous types so you can not possibly specify the variable type that stores their result.

  16. gravatar

    # by Thomas Reasoner - August 5, 2019 at 6:54 PM

    I'll go one step further: why even bother with static typing? The only thing that's important is what an object can do, not what its type is. I could care less if an object is an instance of FooA or FooB as long as it has a method Bar, and the IBar interface guarantees it for us. If we make sure to always return an interface from our methods, then it really makes no sense to prefer explicit type declarations over var.

  17. gravatar

    # by Bryon Lape, Adventurer - February 14, 2020 at 6:54 PM

    I quite agree. I always use it with two exceptions: the implicit type the compiler picks is the object and not the interface I want; I'm told to not use it by some outdated "guide" a company is using.

  18. gravatar

    # by Joe Sixpack - March 29, 2020 at 3:09 PM

    I understand the arguments for and against var but I'll tell you what, I generally find working with code that uses var to be more of a pain for some reason, especially if it's someone else's code that I'm trying to understand. Maybe I'm just too old school

  19. gravatar

    # by Unknown - April 19, 2020 at 2:55 PM

    I fail to understand how eg. Integer keyword would help in problem feet vs meters. Only stoping of using imperial units can help here.

  20. gravatar

    # by Anonymous - May 8, 2020 at 3:29 PM


    Because classes are far more likely to appear in the code. Also I think there aren't other options besides classes and interfaces to be cosidered in this discussion - so it's logical for only one of them to be prefixed (the less often used one) while the other is known by default what it is.

  21. gravatar

    # by Anonymous - May 8, 2020 at 3:32 PM

    "why do we preface interface names with “I” but not class names with “C” ?"

    Because classes are far more likely to appear in the code. Also I think there aren't other options besides classes and interfaces to be cosidered in this discussion - so it's logical for only one of them to be prefixed (the less often used one) while the other is known by default what it is.

  22. gravatar

    # by Martin - September 24, 2020 at 1:04 AM

    Finally I found this! Introducing 'var' is the logical development of a programming language that puts the focus on solving more problems with less words (or letters for that matter). I really do not care what type I got as a result from a method call as long as it does what I need it to - hence the method/property contract, not type.

    I find it sad, that even in 2020 we are still having this discussion.

  23. gravatar

    # by Unknown - February 25, 2021 at 3:34 AM

    My family had two pets, a rabbit and a cat. To feed them, I wrote the code

    class Rabbit { public void Feed() {...} }
    class Cat { public void Feed() {...} }

    My personal favorite was the rabbit, so

    class OurPets { public Rabbit GetMyFavorite() {...} }

    and I could feed it:

    var rabbit = ourPets.GetMyFavorite();

    Well, eventually while getting older, my brain got refactored, the cat now being my favorite, so I updated OurPets to:

    class OurPets { public Cat GetMyFavorite() {...} }

    My feeding method compiled out of the box, and It Just Works. However, when my brother looks at the code, he wonders how the rabbit survives on cat food...

    Bottom line: I do not use var's unless the type is clear from the code, i.e. in case of new.

  24. gravatar

    # by Anonymous - February 25, 2021 at 4:13 AM

    #25: Isn't the problem more the ourPets.GetMyFavorite method? You've got a method with an unspecific name that returns a very specific class. Looks more like an architectural / a class design problem than a problem with using var.

  25. gravatar

    # by Anonymous - February 25, 2021 at 4:33 AM

    #25: Actually, your example code shows the advantages of using var in your case. As ourPets.GetMyFavorite() now returns a Cat, rabbit.Feed() uses the cat's implementation of feed, and thus your cat is fed correctly. :)

    But it indicates, that your variable names are chosen badly (rabbit). In a code review, I would have made you change it to:
    var myFavoriteAnimal = ourPets.GetMyFavorite();

  26. gravatar

    # by Anonymous - February 25, 2021 at 4:36 AM

    PS: GetMyFavorite() should potentially return IAnimal or something like that anyway.

  27. gravatar

    # by Steven Dove - April 9, 2021 at 5:58 AM

    Reason for prefixing interfaces with I is easy enough to understand, it is to avoid naming conflicts with the concrete implementation class names that often accompany them. Could you imagine having to deal with if it was the difference between System.Collections.Generic.Enumerable and System.Collections.Generic.Interfaces.Enumerable?

  28. gravatar

    # by Steven Dove - April 9, 2021 at 6:06 AM

    Make that System.Collections.Generic.Enumerable and System.Linq.Enumerable. I started that with List vs IList and changed to taking about IEnumerable, but neglected changing the namespaces...

  29. gravatar

    # by Anonymous - July 29, 2021 at 6:38 PM

    The essence of this argument is the fundamental of your job as a software engineer. The best engineers make code that is understandable by the next guy that has to read and understand it not how easy it is for you to produce it. Implementation is always in the details so var should only be used where the it is easy to understand what it is exactly at first glance.

  30. gravatar

    # by Anonymous - August 9, 2021 at 4:42 PM

    Well, here we are in 2021 and the question that really remains is: Why not use "var" in all situations?

  31. gravatar

    # by Tom - March 23, 2022 at 7:06 PM

    Why not use "var" in all situations?

    Because at least half of the code is written by less than median skill programmers. And they're probably working on less than average maintained code bases under less than average engineering practices.

    Like many features, 'var' is used badly by mediocre programmers, and since we're the vast majority, the over-all quality of code will drop, and the over all welfare of humanity will be reduced.

    So many new features are added by top-tier programmers *for* top-tier programmers working in companies with excellent engineering practices with nary a thought for how these features will be used (or more likely misused) by the rest of the world's programmers who produce most of the code out there...

    - Signed "The person responsible for mopping up the blood and re-attaching the fingers after the knife company released it's new "two-bladed knife" so that workers can be twice as efficient!"