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{}
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());
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
PersonsMeetingto take anObservableCollection<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: