20

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.

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
thr
  • 19,160
  • 23
  • 93
  • 130

3 Answers3

46

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
8

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`.
Magic1647
  • 143
  • 6
BFree
  • 102,548
  • 21
  • 159
  • 201
1

It works only with local variables as I understand it.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103