Type Inference

Type Inference is a neat feature where the C# compiler can work out itself what type a reference to an object is. While this can be used for the developer to be lazy it is most useful when you are dealing with the exceptionally long type names that LINQ expressions can generate. It is also a requirement when dealing with anonymous types, because there simply is no type name that you can use.

For example:

var aString = “ABC”;
Type st = aString.GetType(); // System.String;

var aNumber = 123.45M;
Type nt = aNumber.GetType(); // System.Decimal

var aDate = DateTime.Now;
Type dt = aDate.GetType(); // System.DateTime

In each of the above examples the compiler works out from what is on the right side of the equals sign the type of the reference (or value) on the left hand side.

What is important is that the compiler has something it can work with. In other words, you must assign something.

var aString; // Illegal – Can’t infer type

// Computer says "no":
// Implicitly-typed local variables must be initialized

Also, because the variable is strongly typed from the get-go each time you assign something to it, it must be of the same type.

var aDate = DateTime.Now;
aDate = 123; // Illegal – Can’t change type

// Computer says "no":
// Cannot implicitly convert type 'int' to 'System.DateTime'

1 Comment

  1. Jon Skeet says:

    I suggest renaming this to “implicit typing” or “implicitly typed local variables”. Personally I tend to associate “type inference” with the inference performed by the compiler when calling a generic method: new List<int> { 5, 10}.Select(x => x.ToString());Here Enumerable.Select<int, string> is called, with the type arguments being inferred.Using var is still inferring a type, but “implicitly typed local variables” makes it clearer which kind of inference you’re talking about.Note that you can’t infer the type of method groups, anonymous functions or null, btw.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s