Explicit operator overload + inheritance
c#, casting, operator-overloading, polymorphism
Solution
You can have your cast operator for type `A` call a virtual (or abstract?) instance method of your `A` instance and override that for each subclass of `A`. `X`, `Y` and `Z` should derive from a mutual base class for this solution, though, so the cast operator can have that base class as a result type.
public abstract class A
{
protected abstract W ConvertToW();
public static explicit operator W(A a)
{
return a.ConvertToW();
}
}
In this example, `W` is a base class of `X`, `Y` and `Z`.
Problem
I have been thinking about a way solve a problem I have and I'm not sure whether it will work or not. Say we have a base class called A and 3 subclass B,C and D. ``` A ^ ----------------- | | | B C D ``` Also we have three classes X, Y and Z. On my system objects type B,C,D are passed as type A and usually I have to convert the Objects of type B,C,D to either objects X,Y or Z (That's not a cast, I manually convert them since they are totally different). Therefore, to convert an Object type A to a type X, Y or Z I need to check the subtype first and then initialize a X, Y or Z Object with the result of some operations about the A Object depending on the subtype. I thought about overloading an explicit cast operation from A to X, Y or Z just doing the same process I was doing when I converted them, but then I thought... Would it be possible to use polimorfism and overload the cast from B,C and D in some way that when I add a new subtype of A I do not need to change the cast code of A?(Just add the explicit cast overload to the new subtype) I hope I have explained myself properly sorry if there is something confusing. NOTE: I will add a cast overload for X,Y,Z