WPF - ObservableCollection casting

I have a method named 'PersonsMeeting' that gets as parameter ObservableCollection of Person. Can I somehow deliver it an ObservableCollection of Employee ? what casting do I need ?

p.s - I don't want to get rid of the ObservableCollection type in the method since I'm using it's functionality.

public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Emp { get; set; }

    public MainWindow()
    {
        Emp = new ObservableCollection<Employee>();

        InitializeComponent();
        PersonsMeeting(Emp); // How Do I Cast this ?!?!?!??
    }

    private void PersonsMeeting(ObservableCollection<Person> persons)
    {
        // ....
    }
}

public class Person{}
public class Employee : Person{}

Answers


Since you already know that every Employee is a Person, you can simply use Enumerable.Cast to cast the elements to the type needed:

PersonsMeeting(Emp.Cast());

PersonsMeeting(new ObservableCollection<Person>(Emp.Cast<Person>()));

But this will most likely not produce the results you expect since you're really creating a new ObservableCollection rather than utilizing the existing one.

Update 2

I notice that the PersonsMeeting method is private and that you're only ever calling it with an ObservableCollection<Employee>.

If that's the case, then you're trying to use an unnecessary abstraction in your private method. You can safely get rid of that and simply modify PersonsMeeting to take an ObservableCollection<Employee>.

The other option is to change the way your class is exposing its data. If you want to keep the abstraction, make your class look like:

public partial class MainWindow : Window
{
    private ReadOnlyObservableCollection<Person> _readOnlyEmp = null;
    private ObservableCollection<Person> _emp = new ObservableCollection<Person>;

    public ReadOnlyObservableCollection<Person> Emp
    {
        if(_readOnlyEmp = null)
            _readOnlyEmp = new ReadOnlyObservableCollection<Person>(_emp);

        return _readOnlyEmp;
    }

    public void AddEmployee(Employee e)
    {
        _emp.Add(e);
    }

    public void RemoveEmployee(Employee e)
    { 
        _emp.Remove(e);
    }
}

Need Your Help

Get superclasses function in Scala

scala functional-programming superclass

What would be a short functional way to get the superclasses of a given Class instance in Scala?