I have three classes with common parent. Let’s say parent is Animal and children are Dog,Cat and Parrot.
And I have one observable collection which contains collection of animals user is working with. Collection contains all animals of same type – user is either working only with all dogs or all cats or all parrots.
So I declared ObservableCollection<Animal> animals and depending on user choices I want to change contents of property animals to ObservableCollection<Dog> or ObservableCollection<Cat> or ObservableCollection<PArrot>. So it doesn’t matter if user currently works with dogs or cats but he can choose all actions animals have in common.
But it doesn’t work. It seems that I can’t assign ObservableCollection<Cat> to Property of type ObservableCollection<animal>. I would think it should work, because animal is supertype of cat, so I can assign cat to animal variable as usual.
Why can’t I do this and how can I solve this problem?
One reason it doesn’t work: if it did work, you could have the nonsense scenario:
Another reason is that it is simply not the case that
ObservableCollection<Dog>inheritsObservableCollection<Animal>– they are just different (parallel) closed generic types ofObservableCollection<>.What is permitted is that some interfaces with “out only” APIs (such as
IEnumerable<T>) can be covariant, so if all you need is to iterate them, you can have:(presumably adding the dogs somewhere else)
Another approach would be to use a non-generic API: