20

I've noticed that the C# compiler doesn't infer second generic parameter.
Example:

C++ template code: (yea I know that templates don't work like generics)

class Test {
public:
template <class T,class V> 
    T test(V v) {
       //do something with v
       return T();
    }
};

int i = 0;
Test t = new Test();
double j = t.test<double>(i); //infers V as int

The templates (and generics) can't infer return type, so in C++ I give it the first template parameter, and the second template parameter is inferred from the variable type.

Now, same example in C#:

class Test {
    public T test<T,V>(V v) where T: new() {
       //do something with v
       return new T();
    }
};

int i = 0;
Test t = new Test();
double j = t.test<double>(i); //Error Using the generic method 'Test.test<T,V>(V)' requires '2' type arguments

But if i use 1 type, I don't have to explicitly specify the type:

class Test {
    public V test<V>(V v) where V: new() {
       return new V();
    }
};

int i = 0;
Test t = new Test();
int j = t.test(i); //OK infers V as int.

So, why can't C# generics infer the second type (while in c++ templates it clearly can) ?
I'm sure it's designed that way (I doubt they the .Net team overlooked this), so why is it designed this way that I must explicitly specify both types?

Edit:

From the discussions we had in the answers so far, both languages support overloading by number of template parameters.

So again, why is C# designed this way ? What's different in the language implementation that doesn't allow to explicitly declare only one parameter ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • Related http://stackoverflow.com/questions/4477636/why-must-i-provide-explicitly-generic-parameter-types-while-the-compiler-should-i http://stackoverflow.com/questions/4003552/partial-type-inference – CodesInChaos Jul 23 '11 at 20:30
  • @CodeInChaos : Thanks for the reference, but there's no real answer there either. "Probably simplifying type inference rules" isn't a real reason. They've done it right in c++, so why not here ? – Yochai Timmer Jul 23 '11 at 20:34
  • Simplification is a very real reason. Compared to C++ C# often chooses the simpler but less general rule. – CodesInChaos Jul 23 '11 at 20:47
  • CodeInChaos: Maybe, but it's an assumption. Can't find any basis to it. – Yochai Timmer Jul 23 '11 at 20:51
  • 5
    @Yochai, why do you expect that the answer to your question is going to be related to something "different in the language implementation"? Presumably the reason this doesn't work as you would like is the same as for every nice-seeming feature that could exist in C# but doesn't. Eric Lippert has written, "My usual response to `why is feature X not implemented?` is that of course all features are unimplemented until someone designs, implements, tests, documents and ships the feature, and no one has yet spent the money to do so." – Kirk Woll Jul 29 '11 at 18:03
  • @Kirk-Woll: That would be an answer too. But I would be happy if someone would have something concrete to back one answer or another. The ones I've got so far (that say it can't be implemented or it will mess something up) just aren't true. The thing is that it's possible to implement, and I'm sure it was thought about, so a concrete answer like "yea we thought about it but would be a pain in the ass to implement" would do. But of course would like it to be valid (someone who knows, and maybe have documentation) – Yochai Timmer Jul 29 '11 at 18:09

3 Answers3

30

C# has been designed to be a slightly less brain-bending language than C++.

In particular, I don't think it's a great idea to compare C# generics to C++ templates for various reasons - they're fundamentally two really quite different approaches to accomplishing similar things in some situations. The C++ approach is certainly flexible in some ways - although it doesn't allow (as I understand it) templates which only exist in binary form, or new template specializations to be created at execution time. Basically the C++ templating approach doesn't sit well with the rest of how .NET fits together.

Now as for why you can't specify some type arguments and allow others to be inferred (which is a language decision rather than a platform decision; I'm sure it would be feasible as far as .NET itself is concerned) - again, I believe this is for the sake of simplicity. Choosing the exact right method and the right type arguments is already extremely complicated in C# - more complicated than most C# developers can get their heads round. It involves:

  • Potentially considering methods up the type hierarchy from the compile-time type of the target
  • Overloading by number of parameters
  • Overloading by the number of type parameters
  • The effect of named arguments
  • The effect of optional parameters
  • The effect of generic type parameter constraints on parameter types (not constraints specified by the target method, note)
  • Method group to delegate conversions
  • Anonymous function conversions
  • Type inference for type arguments
  • Dynamic typing
  • Generic covariance and contravariance

Personally, I think that's enough to get my head around, without allowing yet more possiblities via "M can still be a candidate if it has at least as many type parameters as specified type arguments". Would you also want named type arguments and optional type parameters? ;)

I've looked at overloading quite a lot, following the spec thoroughly etc. I've found areas which make the language designers scratch their heads and try to work out what the compiler should do. I've found areas which the compiler definitely gets wrong. I wouldn't want to add any more complexity here without a really good reason.

So yes, it's basically for the sake of simplicity, and sometimes that's a pain - but often you can work around it. For every potential feature, you need to consider:

  • The benefit of the feature to end developers
  • The cost of the feature to end developers in terms of time spent understanding it
  • The cost to the language designers in designing and specifying it thoroughly
  • The cost to the compiler writers in implementing it correctly
  • The cost to the test team in testing it thoroughly (in conjunction with everything else around overloading)
  • The cost to future potential features (if this one makes the language more complicated, that leaves less "potentially grokable" additional complexity for other features)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    Just a comma would be useful, like `call` ... not really esthetic but already exists in the syntax when specifying generically parameted (?) types –  Feb 08 '16 at 09:34
9

As Dan said, C# doesn't allow you to infer only some type parameters of a generic parameter set. This is likely to enable overloading based on the number of generic parameters (which C# allows, at least for generic classes).

However, you can specify parameters of a generic class, and infer parameters of a generic method within that class. But this workaround isn't always a good solution.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Also c++ allows you to overload template functions. And also allows specialization (which is even more complicated) – Yochai Timmer Jul 22 '11 at 23:10
  • @Yochai: C++ template functions are overloaded by the argument types, which is quite different from overloading based on the number of template parameters. And for classes, template specialization actually unifies the number of template parameters. – Ben Voigt Jul 22 '11 at 23:14
  • You can also overload by number of template parameters. `template T test(V v) { return new T() }; template T test(V v) { U u = new U(); return new T() };` – Yochai Timmer Jul 22 '11 at 23:21
  • @Yochai: That seems like it works, after fixing about eight compile errors. – Ben Voigt Jul 23 '11 at 01:32
  • @Yochai: Your demonstration of overloading on template parameter count. – Ben Voigt Jul 23 '11 at 09:03
  • yea I know it does, sorry about the errors... Just made that up in a minute – Yochai Timmer Jul 23 '11 at 09:09
0

One thing that can help in some cases where one would want to specify some type parameters and have others inferred is to create a generic static class with the parameters one wants to specify, and then within that class have a generic static method with the parameters one wants to have inferred. For example, I have a method which, given a method which is convertable to an Action(T,U,V), along with a T, will generate an Action(U,V) that will call that delegate with the originally-specified T along with the U and V. The method would be invoked as (vb syntax):

  NewAction = ActionOf(Of FooType, BarType).NewAction(AddressOf MyFunctionOfBozFooBar, someBoz)

The compiler can determine one of the generic type parameters using the type of someBoz, even though it needs to have the FooType and BarType parameters explicitly specified.

supercat
  • 77,689
  • 9
  • 166
  • 211