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();
}
}
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;
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