Dominick
Dominick

Reputation: 321

C#: Convert SuperClass to SubClass

I have a class (SuperClass) which is used. For own purposes I designed a SubClass, which adds aditional information for me.

class SuperClass{
}

class SubClass: SuperClass{
}

Now my problem is, that at runtime I want to convert an instance of Superclass into an instance of SubClass. Do Some operations on it and then back to SuperClass. So my question ist, how is it possible to actually convert an instance of SueprClass into an instance of SubClass?

SubClass newItem = superClass as SubClass;

Upvotes: 2

Views: 1855

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

If the instance you are working with was initialized as SuperClass, you can't magically convert it into an instance of a SubClass - that would throw the entire type system out the window.

You can, however, add a way to convert SuperClass to SubClass, but you'll have to write code for that.

One way is to add a constructor to the SubClass that takes in an instance of the SuperClass and whatever additional information the SubClass needs (if it doesn't need additional information, perhaps you better use extension methods instead of inheritance).
Another way would be to write explicit conversion operator.

Upvotes: 3

Related Questions