Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the C# compiler deduce type parameters for return values?

I have this code (minimized for clarity):

interface IEither<out TL, out TR> {
}

class Left<TL, TR> : IEither<TL, TR> {
    public Left(TL value) { }
}

static class Either {
    public static IEither<TL, TR> Left<TL, TR> (this TL left) {
        return new Left<TL, TR> (left);
    }
}

Why can't I say:

static class Foo
{
    public static IEither<string, int> Bar ()
    {
        //return "Hello".Left (); // Doesn't compile
        return "Hello".Left<string, int> (); // Compiles
    }
}

I get an error stating that 'string' does not contain a definition for 'Left' and no extension method 'Left' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) (CS1061).

like image 995
miniBill Avatar asked Oct 10 '14 06:10

miniBill


1 Answers

return "Hello".Left<string, int> (); // Compiles

No surprise. You stated the type parameters explicitly and the compiler is happy.

return "Hello".Left (); // Doesn't compile

No surprise either, compiler has no way to find out what is TR in this case. TL can be inferred because TL is passed as a parameter left but TR cannot.

C# compiler makes no assumptions in what you meant, If the intent is not clear it will throw a compiler error. If compiler thinks you might be doing something wrong it gives a compiler warning.

like image 93
Sriram Sakthivel Avatar answered Oct 19 '22 17:10

Sriram Sakthivel