C# Type Inference


In C# 3, the keyword var was introduced. What does var do? What is type inference? Let’s take a step back to explain this with a bit of review.

C# is a strongly typed language. This means that every variable has a fixed type and can be used only in the code that takes that type into account. You can declare an integer and initialize it at the same time. You can then output it to the console to check that you code is working. You can declare a variable and initialize it later in another statement. When you declare an integer the compiler is aware that your identifier (the name you gave to your variable) is an integer.

Instead of putting int in front of the identifier, you can use var. However, know that there is no type called var. When you use var you are not declaring a variable without a type. You are not declaring a variable of type var. Var is not a type. You are not declaring a type that can change. If that were the case C# would no longer be a strongly typed language.

When you use var you are relying on the C# compiler to determine the type of the variable. If the compiler is unable to determine the type of the variable then it will not compile.