Introduction
I am aware that \"user-defined conversions to or from a base class are not allowed\". MSDN gives, as an explanation to this rule, \"You
Honestly, I think the original request is being misunderstood.
Consider the simple situation where a base class is just serving as a grouping of related classes.
Ex:
class Parent ...
class Child1 : Parent ...
class Child2 : Parent ...
Where the programmer knows how to explicitly convert from one child class to another.
The Parent class can be used, for example, in:
Dictionary
What I think the original request is asking for is:
How to be able to code:
Class1 v1 = ...
Class2 v2 = ...
v1 = v2;
Where inside Parent there is explicit code to do the conversion from Class2 to Class1 objects.
I have this exact situation in my code.
The best I managed to do was to add a property to Parent class that knows how to do the conversion and returns the proper typed object.
This forces me to write my code:
v1 = v2.AsClass1;
Where the property AsClass1 in Parent knows how to do the actual conversion from Class2 to Class1.
Honestly this is a code kludge (its ugly; detracts from from simplicity, can make expressions ridiculously long, obfuscates, and most annoyingly it lacks elegance) but its the best I could come up with.
And, yes, you guessed it, the Parent class also includes the AsClass2 method :-)
All I wanted to do was:
v1 = v2;
and have the compiler silently invoke the method I specified to do the conversion.
I really don't understand why the compiler does support this :-(
In my mind this is really no different then:
int v1;
decimal v2;
. . .
v1 = (int)v2;
The compiler knows to silently invoke some built-in conversion method.