views:

607

answers:

3

Title says it all, 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.

+2  A: 

It works only with local variables as I understand it.

EricSchaefer
+7  A: 

It can only be used for local variables, but it can detect the type in many different forms.

var myVar = SomeMethodThatReturnsInt(); //will know it's an int
var myIntList = new List<int>(); //this works too (although this is technically not type inference)
var myOwnVar = new {Name = "John" , Age = 100}; // will create own type and infer that

EDIT: One more example of Tye Inference is with Lambdas. IE:

var myList = new List<int>();
//add some values to list

int x = myList.Find(i => i == 5); // compiler can infer that i is an int.
BFree
+9  A: 

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