First off, lets make it clear that IBaseClass
is not a base class, its an interface
, which is something quite different. Pointing out the differences is not in the scope of this answer but you can easily read about it, starting here.
That said, as others have stated, you can't do what you want directly. Consider the canonical example IAnimal
, Dog
, Cat
, etc. Evey dog and every cat are animals, but cats are not dogs and dogs are not cats and you are basically asking a cat to be a dog; you first need to teach cats how to dogify (they won't do that out of the box for you).
In order to achieve this behavior there are quite a few ways how you can do it:
User defined cast: You can define operators that convert from one class to another. If you make them implicit
you'd even get your code to compile as it is right now:
public static implicit operator dClass2(dClass1 obj)
{ //logic to convert obj to corresponding new dClass2 instance }
Now this would be legal:
var c1 = new dClass1();
dClass2 c2 = c1; // implicit cast operator is called.
Note that if you were to implement the cast operator as explicit, the former code would not compile. You would need to explicitly cast c1
:
var c2 = (dClass2)c1;
Define a dClass2
constructor that takes a dClass1
argument:
public dClass2(dClass1 obj) { ... }
and you'd write the following code:
var c1 = new dClass1();
var c2 = new dClass2(c1);
Define a static factory method in dClass2
that takes a dClass1
argument and produces a new dClass2
instance:
public static dClass2 CreateFrom(dClass1 obj) { ... }
And the corresponding code:
var c1 = new dClass1();
var c2 = dClass2.CreateFrom(c1);
- Many more I haven't bothered to think about...
Which one you choose is up to personal taste. I'd probably use the explicit cast, but there is nothing inherently wrong with any of the options available.