Reputation: 13344
I have following example structure of classes:
public class Base
{
}
public class Child1 : Base
{
}
public class Child2 : Base
{
}
And I want to do some black magic:
Base @base = new Child2(); //note: there @base is declared as Base while actual type is `Child2`
var child1 = (Child1) @base;
And it fails with System.InvalidCastException
as expected.
Then I added implicit cast operator to Child2
:
public class Child2 : Base
{
public static implicit operator Child1(Child2 child2)
{
return new Child1();
}
}
And code still throws the same exception (explicit operator also does not help).
Do you have any ideas how to fix this behavior without using dynamic
, custom cast method or declaring local variable @base
as Child2
?
Upvotes: 1
Views: 279
Reputation: 14522
You've implemented an implicit cast in Child2, but are trying to cast from Base, actually.
You should first cast it to Child2 so the implicit conversion to Child1 will apply:
var child1 = (Child1)(Child2)base;
OR
Child1 child1 = (Child2)base;
And if you don't know the type:
var child1 = base is Child1 ? (Child1)base : (Child1)(Child2)base;
var child2 = base is Child2 ? (Child2)base : (Child2)(Child1)base;
A completely different approach would be:
public class Base
{
public T As<T>() where T : Base, new()
{
return this as T ?? new T();
}
}
But anyway - this is bad design and you shouldn't, in general, have stuff like that.
I suggest posting your actual need, the thing you are trying to do, with all the details, and ask for a better design/solution.
Upvotes: 2