I have an class named Foo. This class contains a collection of child objects of type FooChildBase, but I also have a further class of type FooChildTwo which inherits from FooChildBase.
Class Foo
Public Children As IList(Of FooChildBase)
End Class
Class FooChildBase
Public Info As String
End Class
Class FooChildTwo
Inherits FooChildBase
Public ExtraInfo As String
End Class
This all works fine. Now I need to use a specialisation of my Foo object with extra information.
Class FooSpecial
Inherits Foo
Public SpecialInfo As String
End Class
Class FooChildSpecial
Inherits FooChildBase
Public SpecialChildInfo As String
End Class
What I would like to do is have my FooSpecial Class treat it’s Children collection as if they were FooChildSpecial objects, but still be able to add FooChildTwo objects to it. Is this possible and if so how can it be done?
EDIT
I think my original question was incorrect. I need to FooChildSpecial class to wrap any of the objects in the Children collection with the extra values, whether they are FooChildBase or FooChildTwo or XXX.
Hope this makes sense! Please let me know if more clarification is needed.
James
In order for FooSpecialChild to “Wrap” FooChildTwo, it either has to inherit from it or implement the same interface (IFooChildTwo). Unfortunately, you cannot conditionally inherit or implement … it is either always or never. As such, your FooSpecialChild class can inherit from FooChildTwo, but then it will always be a FooChildTwo. Same if it implements the same interface as FooChildTwo.
The design pattern you laid out will work correctly. Since both FooChildSpecial and FooChildTwo inherit from the same base class, and the list is of that base class type, it will work out. You’ll just have to check the type of the object when you’re pulling from the .Children property.After copy+pasting your code into a sample project, I could successfully do:
Which shows that you can add both FooChildSpecial and FooChildTwo to your original list.