The curious lack of type inference support in C# constructors

Giv­en a gener­ic class in C# like this one:

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

You will need to spec­i­fy what the type T should be when you call the con­struc­tor:

var myObj = new MyType<int>(42);

The com­pil­er is not able to use type infer­ence to infer the type T to be int.

Now, this is inter­est­ing as type infer­ence is sup­port­ed by any oth­er gener­ic method, so if you were to cre­ate a fac­to­ry class for MyType<T> you could indeed make use of type infer­ence like this:

public class MyTypeFactory
{
    public static MyType<T> Create<T>(T value)
    {
        return new MyType<T>(value);
    }
}
...
var myObj = MyTypeFactory.Create(42); // returns MyType<int>

Some argue that it’s not pos­si­ble because of the pos­si­ble pres­ence of oth­er over­loaded con­struc­tors (or for that mat­ter a non-gener­ic ver­sion of MyType), but at the end of the day the con­struc­tor is a method like any oth­er and the cit­ed ambi­gu­i­ty can also appear with nor­mal gener­ic meth­ods:

public void Foo(short value) {}
public void Foo(int value) {}
public void Foo(long value) {}
public void Foo(double value) {}
public void Foo<T>(T value) {}
…
Foo(42); // which Foo is called? Foo(int) of course!

So amidst all that ambi­gu­i­ty the com­pil­er is able to infer the type for the Foo method, so what’s so spe­cial about the con­struc­tor? Am I miss­ing some­thing obvi­ous here?

Luck­i­ly, as Eric Lip­pert stat­ed in his answer to my ques­tion here, the rea­son the con­struc­tor does not sup­port type infer­ence is a prac­ti­cal one – the ben­e­fit of the fea­ture does not out-weight the cost of its imple­men­ta­tion and it is some way behind oth­er pos­si­ble fea­tures in terms of pri­or­i­ty. Whilst he did say that this fea­ture is on the list, con­sid­er­ing that the ‘theme’ of the next C# release (5.0) is rumoured to be meta-pro­gram­ming, there’s a good chance we won’t be see­ing type infer­ence in the C# con­struc­tor for some time yet!

References:

Jon Skeet’s Brain­teasers + Answers

Stack­Over­flow ques­tion – why can’t the C# con­struc­tor infer type