Letting the C# Compiler Infer Data Types

By John Paul Mueller, Bill Sempf, Chuck Sphar

C#’s compiler is a handy tool. Often, when you declare a variable with C#, you specify it’s exact data type, like this:

int i = 5;

string s = "Hello C#";

double d = 1.0;

You’re allowed to offload some of that work onto the C# compiler, using the var keyword:

var i = 5;

var s = "Hello C# 4.0";

var d = 1.0;

Now the compiler infers the data type for you — it looks at the stuff on the right side of the assignment to see what type the left side is.

For what it’s worth, there is a way to calculate the type of an expression like the ones on the right side of the assignments in the preceding example. Not that you need to do that — the compiler mostly does it for you. Suppose, for example, you have an initializing expression like this:

var x = 3.0 + 2 - 1.5;

The compiler can figure out that x is a double value. It looks at 3.0 and 1.5 and sees that they’re of type double. Then it notices that 2 is an int, which the compiler can convert implicitly to a double for the calculation. All the additional terms in x’s initialization expression end up as double types. So the inferred type of x is double.

But now, you can simply utter the magic word var and supply an initialization expression, and the compiler does the rest:

var aVariable = <initialization expression here>;

If you’ve worked with a scripting language such as JavaScript or VBScript, you may have gotten used to all-purpose-in-one data types. VBScript calls them Variant data types — and a Variant can be anything at all. But does var in C# signify a Variant type? Not at all. The object you declare with var definitely has a C# data type, such as int, string, or double. You just don’t have to declare what it is.

What’s really lurking in the variables declared in this example with var? Take a look at this:

var aString = "Hello C# 3.0";


The mumbo jumbo in that WriteLine statement calls the String.GetType() method on aString to get its C# type. Then it calls the resulting object’s ToString() method to display the object’s type. Here’s what you see in the console window:


The output from this code proves that the compiler correctly inferred the type of aString.

Most of the time, the best practice is to not use var. Save it for when it’s necessary. Being explicit about the type of a variable is clearer to anyone reading your code than using var.

You can see var used in other ways: with arrays and collections of data, and with anonymous types. Anonymous? Bet you can’t wait.

What’s more, a type in C# 4.0 and later is even more flexible than var: The dynamic type takes var a step further.

The var type causes the compiler to infer the type of the variable based on expected input. The dynamic keyword does this at runtime, using a set of tools called the Dynamic Language Runtime.