Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# type inference : fails where it shouldn't?

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?

like image 358
sandesh247 Avatar asked Dec 02 '22 08:12

sandesh247


2 Answers

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)
like image 110
Vojislav Stojkovic Avatar answered Dec 04 '22 14:12

Vojislav Stojkovic


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.

like image 33
Jon Skeet Avatar answered Dec 04 '22 13:12

Jon Skeet