Coen Adrien van Driel

I'm a software architect and software quality & testing enthusiast. My focus is on using Microsoft technologies from C# to Azure to create awesome products.

I'm also the founder of ExpertSwitch, a software consulting company.

What Is The VAR Keyword In C# and Best Practices

September 29, 2019

Do you have a solid understanding of the pro’s and con’s of using var in C#? If yes, ignore this article and proceed as you were. If you’re in doubt whether you should use var or curious about the effects of using var, this is the article for you.

Introduction to VAR

When in 2007 C# 3.0 was launched, var was introduced as a new C# keyword. With C# being a statically typed programming language, var opened the door for a more dynamically typed ‘feel’ to programming in C#. Many who are familiar with using var in dynamically typed languages like JavaScript had to wait for one later version of C#, version 4.0 in 2010, for the introduction of the dynamic keyword to get some true dynamically typed programming done in C#.

The basic usage of var is to essentially ‘shorten’ the type declaration to var and let the compiler figure out the correct type at compile time based on the right-hand side of the assignment. You can consider var in C# a way to implicitly type your code. It is often called syntactic sugar because it ‘just looks nice syntactically’ and does not change the underlying behaviour of the code. Even though var was originally introduced for use of anonymous types, it has become very popular to use var, and thus implicit typing, as the default way to declare types.

VAR example usage

//both lines result in the same compiled code
var s = “hello world” // implicit typing
string s = “hello world” // explicit typing

//var can also be used with custom types and method calls
var v = GetMyType() // implicit typing
MyType v = GetMyType() // explicit typing

//The original use case for var, anonymous types, often used with LINQ
var query = from item in items
	select new { item.Name, item.Price };

//plain anonymous object instantiation
var v = new { Name = “John”, Age = 19 }

Statically vs dynamically-typed, VAR vs DYNAMIC

The differences between statically typed programming languages and dynamically typed languages is fairly straight forward. With statically typed languages, not be confused with strongly or weakly typed, types are checked at compile time, with dynamically typed languages types are checked runtime. The benefit of statically typed languages is that type errors can be detected early and prior to running the code, but dynamically typed languages offer more flexibility with, you guessed it, the use of types and can result in more concise code. The confusion with var in C# in regards to type inference is easy to understand considering that var also exists in other languages, like JavaScript, where it is used in a dynamically typing style.

Because C# now also has the dynamic keyword, you can actually do some dynamic-typing in C# in a similar way you can do in JavaScript. This makes C# both a statically and dynamically typed language.

When to use DYNAMIC?

In most of your C# programming the use of dynamic should be avoided to leverage the benefits that C# has to offer in regards to type safety. In some cases, mostly when dealing with other non-C# and/or unmanaged code, dynamic can be needed.

Dynamic example usage

MyType t = new MyType() // is type checked at compile time
dynamic t = new MyType() // is type checked at run time

// compiler errors will not show and prevent errors during development when using dynamic
// the compiler will not give errors on calling non existent properties or methods, misspelling method names can easily result in unnoticed errors
// let’s use an example where MyType as a method called MyMethod, but we accidentally misspell it by calling MyMetod().
MyType t = new MyType() //
t.MyMetod() // misspelling the method name will result in a compile time error, usually alerted via your IDE.

//dynamic example
Dynamic t = new MyType() // is type checked at run time
t.MyMetod() // misspelling the method name when using dynamic will now show errors in your IDE, only at runtime exceptions will occur.

Performance impact of using VAR in C#

Will using var in C# slow down your code? No, because at compile type it results in the same code as if you had explicitly typed your code. Using the dynamic keyword does have some performance implications though.

To use VAR or not to use VAR

This seems to be a never ending debate, it seems that when tools like Resharper started to ‘suggest’ using var by default, everyone jumped ship without truly thinking about it. When I talk to other developers about their use of var they often use it because implicit typing was just how it was done in their (previous) project, or they just like the way it looks (shorter, better ‘visual alignment’) or they flipped a coin and could go either way. All are superficial arguments in my opinion as I think there are solid benefits of not using var (i.e. opting to use explicit typing) in most cases.

Why you should use VAR

Anonymous types

The most objective case, and original C# use case, for using var is when working with anonymous types, as shown in the first code example at the top of this page.

Less code, better visual alignment

Using var means in most cases less typing than explicitly using types. Especially with longer, nested types like dictionaries and nested types, simply using var can save some keystrokes. Also the fact that when listing multiple variables, using var for all of them will result in a ‘neater’ looking piece of code.

To prevent redundant type information

In some basic cases, using explicit typing adds very little additional type information because it is obvious from the code what type is used. For example, var myNumber = 5; vs int myNumber = 5; is not that different in terms of visual type information.

Renaming types becomes easier

When using var everywhere, renaming types because easier as there is no fixed reference to your type, rename your type and at compile time everything will work again. Now, with modern IDE’s and tools like Resharper, doing a bulk rename-operation is very easy and kind of makes this a moot argument.

Why you should NOT use VAR

Using var obscures type information

This is the biggest downside of using var in my opinion and especially when working in a team of other developers, this can really slow down code reviews, and code readability in general.

When reading code, especially other people’s code, readability and clarity is key in quickly grasping the logic, concepts and general intent of the code. Not showing type information adds a layer of uncertainty when trying to understand the code. Using explicit typing really shows its value with method calls. With method calls the return type is hidden and can otherwise only be discovered via your IDE by hovering or goto-definition-action.

var data = GetPersonalDetails() // what return type?
IList<PersonalDetail> data = GetPersonalDetails() // clear type information

Yes you can hover your mouse over the type or go to the definition in your IDE, but that exactly proves the point of lowered readability and clarity if you need to interact with the IDE just to understand fundamental information. Consider that when doing code reviews in online editors like Azure DevOps where hovering or goto-definition-actions are not possible, not having type information can be quite the hindrance to a smooth code review.

Using var requires even more emphasis on proper naming

When using var, type information is obscured as pointed out in the previous argument, this means that if you still want to display fundamental information in regards to the type or meaning, you only have the variable name to do so. Naming is very important, but it is also difficult. Displaying the type information by way of explicit typing relieves a bit of pressure of the already difficult naming task.

Type usage and awareness

Types are a fundamental part of programming and understanding what types are used is key in proper software development. Using implicit type, in a way, takes off the pressure and general awareness of proper type usage. Using the interface, or the implementation, using IEnumerable or List, int, long or short, these differences matter and type-sloppiness generally results in unthoughtful programming (or is it the other way around...).
Finally, there are also cases where explicit typing is required, when using inheritance, nullable types, or when using type variants (long, short, instead of int).

    IMyDataSource dataSource = new MyDataSource();
    Drawing square = new Square();
    int i = 8;
    long i = 8;
    short i = 8;
    int? i = 8;
    int? i = null;

Best practices and suggested conventions

As there are both reasons to use var and to not use var, there are developers using var and not using var, and there are those in between. The suggested var usage-convention I go by are based on a development team’s perspective (as opposed to an individual project). I read other people’s code and they read mine, so readability is key, even in online editors likes Azure DevOps that don’t have the option to click and hover on types.

Because I’m reasoning from a team’s perspective, code consistency and ease of understanding (the rules and conventions) also play a major part. I want to keep exceptions (to the rule) to a minimum and create very little room for personal interpretation as it will almost always lead to personal preference per situation, and thus inconsistency throughout the codebase.

Sometimes using explicit typing adds little extra type information, sometimes you have to write a bit more code (with complex declarations). But, strictly using explicit typing (so NOT using var) comes with the benefit of having clear and easy to understand conventions with little exceptions. More importantly, explicit typing adds fundamental type information to your code, improves readability significantly and results in greater code consistency throughout your entire project. That is why I suggest using explicit typing by default and avoiding the use of var except, and only except, for anonymous types.

Leaving room for personal interpretation on whether to use var or not for each specific case results in unnecessary ‘line of code-level’ decisions and general inconsistency (among team members) with no upside. Keep it simple.

General rule: Never use VAR (always use explicit typing), except for anonymous types.

Below I have listed the most common examples of when to use var and when not. As mentioned, I suggest to not use var at all unless for anonymous types.

Convention overview of explicit and implicit type usage


//simple declarations, use EXPLICIT typing
string s = “hello world”
int i = 8;
long i = 8;
short i = 8;
int? i = 8;
int? i = null;
MyType t = new MyType();

//complex declarations, use EXPLICIT typing
IDictionary<int, string> dict = new Dictionary<int, string>();
Dictionary<int, string> dict = new Dictionary<int, string>();

IList<KeyValuePair<int, int>> data = new List<KeyValuePair<int, int>>();
List<KeyValuePair<int, int>> data = new List<KeyValuePair<int, int>>();

//inheritance and polymorphic declarations, use EXPLICIT typing
IMyDataSource dataSource = new MyDataSource();
Drawing circle = new Circle();
Drawing square = new Square();

//arrays, including shorthand syntax, use EXPLICIT typing
string[] words = new string[] { "car", "train", "plane", "boat" };
string[] words = { "car", "train", "plane", "boat" }; // alternative syntax
int[] array = new int[5];
int[] array = new int[] { 1, 2, 3, 4, 5 };
int[] array = { 1, 2, 3, 4, 5 };// alternative syntax
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 } }; //multi dimensional
int[][] array = new int[4][]; //jagged

//method calls, a very strong use case for explicit typing, thus use EXPLICIT typing
IList<PersonalDetail> data = GetPersonalDetails()
string message = GetMessage()

//loops, use explicit typing
for (int i = 0; i < 5; i++)

foreach(KeyValuePair<string, string> kvp in myDictionary)
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

//LINQ queries without anonymous types, use EXPLICIT typing
IEnumerable<Customer> queryAllCustomers = from cust in customers
                                                select cust;


//LINQ queries WITH anonymous types, use var (IMPLICIT typing)
var query = from item in items
	            select new { item.Name, item.Price };

//anonymous types in general, use var (IMPLICIT typing)
var v = new { Name = “John”, Age = 19 }

Thanks for reading!

If you want to stay in the loop when I post new articles, follow me on facebookFacebook or twitterTwitter Was this article helpful or do you have any questions? Leave a comment!