Search code examples
c#wpfobservablecollectionradixderived-class

How can I call a method for a derived class?


In Short

I want to be able to call a method, the method takes a parameter of type ObservableCollection<Base> but I want to call it with ObservableCollection<Derived>. It says it cannot convert between the two.

Longer

I want to call a WPF Window, in it is a ListBox that will bind to an ObservableCollection. I want the window to display some basic information that are common to two different classes. The classes are Derived1 and Derived2, and are based an BaseClass. I am able to call the method had the type just been BaseClass, but I want to pass a list through.

So I have two collections :

ObservableCollection<Derived1> A;
ObservableCollection<Derived2> B;

And want to be able to call a method like the one below, with the above two collections so I don't need to duplicate code.

public void InitialiseWindow(ref ObservableCollection<BaseClass> List)
{
    this.List=List;
}

But it throws an error:

cannot convert from 'ref System.Collections.ObjectModel.ObservableCollection<Derived1>' to 'ref System.Collections.ObjectModel.ObservableCollection<Base>'

Whilst I'm here

Would there be a better way of binding the Collection so changed made in the Window will reflect on the source, instead of using ref?

Solution

I modified the constructor for the Window so that it casts the IEnumerable to a public member of type ObservableCollection. Since the window would only be shown modally, this the member could be accessed after the window closes.

public ObservableCollection<BaseClass> List;

public InitialiseWindow(IEnumerable<BaseClass> List)
{
    InitializeComponent();
    this.List=new ObservableCollection<BaseClass>(List);
}

Solution

  • If you're exposing it purely for binding purposes, it's sufficient to pass an IEnumerable<BaseClass> reference. The data binding system will automatically inspect the actual instance to see if it implements INotifyCollectionChanged, so it does not need the bound property to be typed explicitly as an ObservableCollection.