1

So I have a

BaseClass

and several child classes that inherit from the baseclass

ChildClass1
ChildClass2

I have ObservableCollections of child classes that need to be sorted in place, I cannot create a new ObservableCollection<ChildClas1>.

So i wrote a function

private void Reorder(ObservableCollection<BaseClass>)
{
   //sort the collection in place
}

then i do Reorder(ObservableCollection<ChildClass1>)

the compiler is complaining that it cannot convert System.Collections.ObjectModel.ObservableCollection<ChildClass1> to ObservableCollection<BaseClass>

I will take the compilers word for it, but how can I achieve this without having to duplicate my reorder function for every single child type?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
user1336827
  • 1,728
  • 2
  • 15
  • 30

1 Answers1

7

I will take the compilers word for it

The reason why you cannot pass a collection of one type to substitute for a collection of another type is discussed in many Q&As on SO - for example, here.

how can I achieve this without having to duplicate my reorder function for every single child type?

One approach is to make your Reorder generic on the type of collection element, and add a constraint to the type parameter to specify that objects must derive from your base class:

void Reorder<T>(ObservableCollection<T> collection) where T : BaseClass {
    ...
}
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523