class Base
{
}
class Derived1 : Base
{
}
class Derived2 : Base
{
public static explicit operator Derived1(Derived2 d2)
{
return new Derived1();
}
}
class Test
{
static void Main()
{
Base bd2 = new Derived2();
Derived1 d2ConvertedD1 = (Derived1)bd2; //throws InvalidCastException
}
}
Unable to cast object of type 'ConsoleApplication1.Derived2' to type 'ConsoleApplication1.Derived1'.
Why? What is wrong with my operator conversion?
Look at the signature of your operator:
Notice it's static. What you're seeing is similar to the limitation of method overload resolution.
It's essentially the same reason the below outputs "Object" instead of "String":
That is, the compiler needs to pick an overload at compile-time. In the case of casting from a
Baseto aDerived1, there is no overload with the proper signature, so it attempts an actual downcast. Declaringbd2asDerived2, as others have mentioned, would "fix" this by enabling the compiler to select your custom conversion.