Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Explicit Operator Not Invoked In Generic Method

Tags:

c#

generics

I've distilled this question down to the simplest code sample I can think of. Why is the explicit operator not invoked from the generic method?

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = (B)a; // works as expected
        b = Cast<B>(a);
    }

    static TResult Cast<TResult>(object o)
    {
        return (TResult)o; // throws Invalid Cast Exception
    }
}

class A
{
}

class B
{
    public static explicit operator B(A a)
    {
        return new B();
    }
}
like image 649
John Kraft Avatar asked Jan 09 '13 20:01

John Kraft


1 Answers

Because a generic method has one set of IL, based around TResult. It doesn't do different IL per-caller. And the generic TResult does not have any operators.

Also: the operator here would need to be between object and TResult, and you can't define operators involving object.

For example: Cast<int> and Cast<string> and Cast<Guid> all have the exact same IL.

You can cheat with dynamic:

return (TResult)(dynamic)o;
like image 150
Marc Gravell Avatar answered Oct 19 '22 22:10

Marc Gravell