Var is an implicit type. It aliases any type. The aliased type is determined by the C# compiler. This has no performance penalty. Var is excellent (and tasty) syntactic sugar. It makes programs shorter and easier to read.

Example. First we look at some examples of the var keyword. Here is a code example of the var keyword being used in three contexts. Please note that you need a recent version of the .NET Framework to compile this program.

Next, we see the var items query. It returns IEnumerable<int>. The query expression is evaluated to this type—and var implicitly refers to that type. You can use var with the foreach-loop. You can use it like any other variable.

Tip: The var keyword can represent any type that can be determined at compile-time. It is precisely equivalent after compilation.

Type systems. The C# language has a strong type system. This means that memory is labeled by what kind of object it contains. The language uses strong types to enforce code quality. Variables are both memory and also type annotations.

So: The C# compiler raises errors and warnings because it wants your code to work properly.

And: It makes inferences about your code and can deduce the type of a variable.

Brevity: Languages sometimes have lengthy keywords. You can reduce this with var—it's only three letters.

Limitations. Next, we consider some interesting limitations of the var keyword. You can't assign a var to null. This will result in the CS0825 warning. You also can't use var as a parameter type or a return value of a method.

Implementation. Next, we look at the internal implementation and behavior of the var keyword. C# code is turned into IL. You can see it with a utility called IL Disassembler provided with Visual Studio. There are two int32 values in the IL below.

Uses. One tip is to use var on generic types. The Dictionary type has verbose syntax—it uses a lot of brackets and letters and a comma. Some code becomes much easier to read with this keyword. Var can even make code refactoring easier.

Tip: If you change a type name with refactoring, a var type local will not need to be changed.

Dictionary. Var simplifies the syntax of generic types. It is particularly useful for generic collections such as Dictionary. It allows you to omit the long type parameter lists. This simplifies the syntax of your code. It improves readability.

Var is a handy keyword. We find out what it stands for by hovering over it in Visual Studio. It has similarities to #define or typedef in C++. We use var for brevity. It makes the code easier to understand.