11

Why does C# infer generic parameters for methods but not for constructor?

new Tuple<int, int>(5, 5) vs. Tuple.Create(5, 5)

SiberianGuy
  • 24,674
  • 56
  • 152
  • 266

2 Answers2

9

The other answers are wrong. There is no technical reason for this. The type could be inferred from the constructor call as it can from "normal" method calls.

Please refer to the answer by Eric Lippert (former C# compiler developer): Why can't the C# constructor infer type?

Community
  • 1
  • 1
Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
5

Consider the following:

public class Foo<T>
{
    public Foo(T value) { }
}

public class Foo
{
    public Foo(int value) { }
}

// suppose type parameter inference in constructor calls
var x = new Foo(5); // which one?

Because you can declare two types with the same name, one generic, and one non-generic, you need to unambiguously decide between them in the constructor call. Forcing the type parameters to be explicit is one way to remove any possible ambiguity. The language could have some resolution rules for this, but the benefits of this feature enough to spend the budget to implement it.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • 6
    Good example. But what if we have two method overloads: generic and not generic? I don't see a big difference here – SiberianGuy Mar 25 '11 at 09:58
  • 2
    The same one that would be called if they were methods -- the non-generic. – Jon Mar 25 '11 at 09:59
  • 2
    Jon is correct. From this point of view a constructor call is nothing else than any other method call and same inferring rules could be applied. – Florian Greinacher Mar 25 '11 at 10:24
  • 1
    Though indeed confusing cases such as this one exist, as an answer this is incorrect - see Florian's answer instead. (comment added since this is currently the most upvoted answer). – Eamon Nerbonne Mar 25 '11 at 10:35