Notice the following code. The offending line has been commented out.
interface I<R> { }
class C : I<int> { }
class Program
{
private static void function<T, R>(T t) where T : class, I<R>
{
}
static void Main(string[] args)
{
// function(new C()); // wont compile
function<C, int>(new C());
}
}
I believe type inference should figure out the type because the argument T
provides the first type, while I<R>
provides the second type.
Is there a way to redesign the function so that the callers may not have to specify the types?
Not if you want to keep all the constraints. However, this should serve equally well, unless you have a specific reason to forbid value types:
private static void function<R>(I<R> t)
There are various ways you could add extra rules to type inference - bits of logic that a human can apply but which the compiler (obeying the language spec) doesn't.
Before you suggest that the language really should be updated to make type inference work more flexibly though, I strongly suggest that you read the existing spec. If you can understand that sufficiently easily that you still think it's worth making it even more complicated, post a feature request on Connect - but personally I think it's quite complicated enough already. I would say that it's a lot better than it was in C# 2.0.
To put forward the opposing view, however - several languages (particularly functional ones) have more powerful type inference mechanisms. There are always pros and cons here - I believe one of the benefits of the current inference system in C# is that it always makes progress or stops, for instance - Eric Lippert's blog has more information on this and a number of other type inference issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With