How good is the C# type inference?

thr picture thr · Jan 26, 2009 · Viewed 8.9k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Jan 26, 2009

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 :)