Stuff that's in my head

Can open... Worms? everywhere! The blog of Colin Angus Mackay
posts - 379, comments - 486, trackbacks - 52

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'

Print | posted on Friday, March 19, 2010 11:45 AM

Feedback

Gravatar

# re: Type Inference

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.
3/19/2010 12:00 PM | Jon Skeet

Post Comment

Title  
Name  
Email
Url
Comment   

Powered by: