I\'m trying to write generic method to cast types. I want write something like Cast.To instead of (Type) variable.
My wrong versi
Instance a is an object to the moment of casting to B. Not A type, but object. So, it is impossible to cast object to B because of CLR can not know, that o contains explicit operator.
EDIT:
Yeah! Here is solution:
public class Cast
{
public static T1 To<T1>(dynamic o)
{
return (T1) o;
}
}
Now CLR exactly knows, that o is an instance of type A and can call the explicit operator.
You will never get this to work without a 'type converter'(a manual process of mapping across attributes for all known types which simply will not happen). You simply cannot just cast one non-related concrete class to another. It would break the single inheritance model (which is one of the defining principles of modern OOP - read up on 'the Diamond Problem')
It was also noted about interfaces (polymorphism) - both classes would have to derive from the same interface also (which is along the same lines)