How good is C# type inference? I read somewhere that it's only for local variables? Does it work for class level attributes? For method signatures? Method return types? etc.
3 Answers
There are a few main kinds of type inference in C#:
- Implicitly typed local variables: - Only for local variables
- Only when the value is assigned as part of the declaration
- Value cannot be null
- Value cannot be a lambda expression, anonymous method or method group (without a cast)
- The compile-time type of the value is used for the type of the variable
- Any further uses of the variable are only checked against the type determined by the initial declaration+assignment; they don't contribute to the inference itself.
 
- Generic method type argument inference, i.e. you don't specify the type arguments in a call to a generic method, the compiler figures them out based on the arguments. - Would be really handy to have this for generic types as well as generic methods
- Really handy anyway - LINQ would be hard or impossible to use without it
- Anonymous types would be fairly useless without it
- Really complicated rules, even the spec is wrong in a few places
 
- Lambda expression parameter type inference - Compiler tries to work out the types of the parameters for lambda expressions based on the context in which it's used
- Usually works pretty well, in my experience
 
- Array type inference, e.g. - new[] { "Hi", "there" }instead of- new string[] { "Hi", "there" }- Various small restrictions, nothing major
 
I've probably forgotten some other features which might be called "type inference". I suspect you're mostly interested in the first, but the others might be relevant to you too :)
 
    
    - 1,421,763
- 867
- 9,128
- 9,194
It can only be used for local variables, but it can detect the type in many different forms.
var myVar = SomeMethodThatReturnsInt(); // `myVar` will be deduced as an `int`.
var myIntList = new List<int>(); // `myIntList` will be deduced as a List<int>.
var myOwnVar = new { Name = "John", Age = 100 }; // `myOwnVar` will be deduced as an AnonymousType.
Notice: When you work with anonymous types, you must declare variable with
var.
Another example of Type Inference with Lambda expressions:
var myList = new List<int>();
// <add values to list>
int x = myList.Find(i => i == 5); // `i` will be deduced as an `int`.
- 
                    3Why the second example is not technically type inference? – Rafa Castaneda Feb 03 '11 at 17:50
- 
                    +1 to Rafa Castaneda. Why is the second example not an example of type inference? it certainly looks like it to me! – TheIronKnuckle Oct 24 '16 at 03:35
 
     
     
     
    