193

Why is type inference not supported for constructors the way it is for generic methods?

public class MyType<T>
{
   private readonly T field;
   public MyType(T value) { field = value; }
}

var obj = new MyType(42); // why can't type inference work out that I want a MyType<int>?

Though you could get around this with a factory class,

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

Is there a practical or philosophical reason why the constructor can't support type inference?

5
  • 2
    I had the same question two years before this one: stackoverflow.com/questions/45604, so technically this is a duplicate. Eric's answer is excellent and complete though. Commented Jul 4, 2013 at 9:09
  • If you are trying to pass multiple classes for a strongly typed view, try this: return View(Tuple.Create(new Person(), new Address())); Commented Feb 1, 2016 at 17:08
  • This is the correct answer in my opinion. Since it is the only one that gives a pragmatic solution. A solution that can be used in real life. Using the factory pattern. Even better if you name your factory the same as your generic type. Commented Sep 7, 2016 at 17:16
  • Please vote for the feature request! Proposal: Constructor type argument inference Commented Jun 14, 2018 at 9:55
  • BTW: It's important to realize the Factory class can have the same name as the results class, and if it's being used just as a factory you can make it static eg. public static class MyType. For my use-case this becomes QueryResults.FromResults(orders, data) which returns QueryResults<Order[], Data> Commented May 29 at 2:22

5 Answers 5

148

Is there a philosophical reason why the constructor can't support type inference?

No. When you have

new Foo(bar)

then we could identify all types called Foo in scope regardless of generic arity, and then do overload resolution on each using a modified method type inference algorithm. We'd then have to create a 'betterness' algorithm that determines which of two applicable constructors in two types that have the same name but different generic arity is the better constructor. In order to maintain backwards compatibility a ctor on a non-generic type must always win.

Is there a practical reason why the constructor can't support type inference?

Yes. Even if the benefit of the feature outweighs its costs -- which are considerable -- that's not sufficient to have a feature implemented. Not only does the feature have to be a net win, it has to be a large net win compared to all the other possible features we could be investing in. It also has to be better than spending that time and effort on bug fixing, performance work, and other possible areas that we could put that effort. And ideally it has to fit in well to whatever the "theme" is of the release.

Furthermore, as you correctly note, you can get the benefits of this feature without actually having the feature itself, by using a factory pattern. The existence of easy workarounds makes it less likely that a feature will ever be implemented.

This feature has been on the list of possible features for a long time now. It's never been anywhere near high enough on the list to actually get implemented.

UPDATE March 2015

The proposed feature made it close enough to the top of the list for C# 6 to be specified and designed, but was then cut.

Sign up to request clarification or add additional context in comments.

21 Comments

It's still a bit odd and inconsistent, IMO the language benefits of features being implemented consistently. But that's just my opinion.
@Triynko: Oh good heavens no, the C# compiler fails to make all sorts of possible inferences. For example, class B<T> { public virtual void M<U>() where U : T {} } class D : B<int> { public override void M<U>() {} } ... (new D()).M(); -- you and I can use our mental type inference to know for darn sure that the only possible type argument is int, but the C# compiler misses that trick. I could list examples all day; our type inference is quite weak compared to F#.
@Triynko: Or short M<T>(out T y){...} ... var x = M(out x); You and I can reason that the only possible return type is short, and therefore x must be short, and therefore T must be short. But the C# compiler falls over immediately if there is any cycle in an implicitly typed local.
Or void M<T>(T t1, T t2){} ... M(new Giraffe(), new Turtle()); You an I can reason that the writer of the code probably intended T to be Animal, but the C# compiler does not reason "Giraffe and Turtle share a common base type Animal, therefore it is the best candidate for T".
Language consistency is a priority, but it is a low priority compared to more pragmatic concerns. And I assure you that we have a list literally longer than your arm of features that take one sentence to describe; had we twenty times the current budget we still would not want to implement everything on that list! You would not want to use a language where every possible feature that could be added was added, believe me. We choose how to spend our limited effort extremely carefully to provide the maximum value for customers.
|
17
public class MyType<T> 
{ 
   private readonly T field; 
   public MyType(T value) { field = value; } 
} 

they can, there is no need to tell the constructor 'what T is' again, seeing as you have already done that in the class decleration.

also your factory is incorrect, you need to have public class MyTypeFactory<T> not just public class MyTypeFactory - unless you declare the factory inside the MyType class

Edit for update:

Well, is 42 a long, a short, an int, or something else?

Let's say you have the following

class Base
{
   public virtual void DoStuff() { Console.WriteLine("Base"); }
}

class Foo : Base
{
   public override void DoStuff() { Console.WriteLine("Foo");  }
}

Then you did this

var c = new Foo();

var myType = new MyType(c);

Would you expect foo to be used, or base? We need to tell the compiler what to use in place of T

When you really wanted to on type base

Hence the

var myType = new MyType<Base>(c);

9 Comments

good point, I meant to say why can't the compiler infer the type using the constructor, updating my question. the factory doesn't have to be generic though
See my edit, if the factory is created inside the MyType Class it knows what T is, but if it's not, you will need T
The compiler can not infer the type because there could me multiple constructors. To augment your example, how would the compiler know which constructor to call when MyType(double) is present?
@PostMan - but in the Create method the compiler can simply infer that T is int
@PostMan: The part of your answer I'm disagreeing with is <quote>your factory is incorrect, you need to have public class MyTypeFactory<T> not just public class MyTypeFactory - unless you declare the factory inside the MyType class</quote> Actually, the correct thing is MyTypeFactory.Create<T> as the question now has, and not MyTypeFactory<T>.Create which you said was needed. Using MyTypeFactory<T>.Create would prevent type inference, since the generic parameter appearing before the member reference operator . cannot be inferred, the one on a method can.
|
12

The main reason generic type inference can't work on constructors like you wish is because the class "MyType" doesn't even exist when all you've declared is "MyType<T>". Remember it is legal to have both:

public class MyType<T> {
}

and

public class MyType {
}

Both would be legal. How would you disambiguate your syntax if you did in fact declare both, and both of them declared a conflicting constructor.

4 Comments

"How would you disambiguate your syntax". In this case, you would have to specify T.
But in the case of the question (and in my case) there is only a single class (that's generic). There is no ambiguity. If I have var myVariable = new MyClass(), how does the compiler know not to make myVariable of type Object or a base class of MyClass? All of the contrary cases presented in these answers don't really explain why it can't infer the type from the local code around a constructor... then if it gets it wrong, the coder makes it more explicit... just like in any other case where the type is inferred. It is always possible to override the default choice if necessary.
@CPerkins sure, and then if you ever create a non-generic version, all consumers using your suggested syntax would now have compiler errors.
@KirkWoll Sometimes it is valid to say "If you do this, then something bad might happen, so it's not allowed", but that type of reasoning doesn't stand especially when there are so many other situations where changes in a class or method declaration will break something. Take basic overrides. It's possible to declare an additional override that creates ambiguity and breaks existing code. So what? It requires refactoring or some alternative solution, not a decision beforehand to disallow overriding methods in the first place.
0

The constructor needs to have the same generic specification as the class itself. Otherwise it would be impossible to know if the int in your example would relate to the class or to the constructor.

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

Would that be class MyType<T> with constructor MyType(int) or class MyType with constructor MyType<T>(T)?

2 Comments

This ambiguity can appear also with normal generic methods.
It would not be impossible to know in most cases. In cases where it could not be unambiguously determined which was intended then we could give an error. This is the same as any other overload resolution problem; if insufficient information is supplied then we simply give an error.
0

Although this has been answered many times before, I feel I need to clarify one thing: C# supports generic type inference on constructors. The problem is, it doesn't support neither adding generic parameters to constructors nor type generic type inference. Wanting to infer generic type argument of the type itself is basically the same as requiring Foo.Bar(0) to infer to Foo<int>.Bar(0).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.