C# constructor generic parameters inference [duplicate]
Why does C# infer generic parameters for methods but not for constructor?
new Tuple<int, int>(5, 5)
vs. Tuple.Create(5, 5)
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?
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.
精彩评论