I have two custom objects, lets say Cat and Dog. I want to create an observable collection that can hold either of these objects, as they are very similar. Can I use base classes to do this?
If so, would you mind providing a quick example.
And if I do use a base class, does that mean if I want to use common fields, I should put those into the base class?
EDIT: I’m hoping to then bind a WPF datagrid to the properties of these objects. I don’t know if it’s possible to bind a datagrid in WPF to two different kind of objects…
Yes, in that case you can use a base class:
Notice however, that when you place instances of both classes in one collection you can access only members of the base class.
So this code is valid:
but you cannot use methods Meow() and Bark() unless you use explicit casting.
Be careful with moving too many members to the base class – in the example above Meow() doesn’t make sense for the Dog and Bark() for the Cat. If you need to use some method specific to the derived class you could check the type with:
and then cast object to the derived type: