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>();

        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(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)

    public void RemoveEmployee(Employee e)

Need Your Help

Can't get view to set elements of LISTVIEW

android listview simplecursoradapter listactivity

have problem with 'listView'. I searched everywhere but the problem does not arise none. Let me explain:

REGEX - collapse any combination of non-alphanumeric symbols into a single “.”

regex autohotkey

I desire to collapse any combination of TWO OR MORE non-alphanumberic characters into a single "."

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.