Archives

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.

Like this:

Related

Post navigation

One thought on “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.