Search code examples
c#.netwinformsdesign-patternsilist

Use inherit class for instance List in C#


Hello stackoverflow community!

Let's start!

I have one small class Person:

class Person
{
    public string name { get; set; }
}

Аnd it has a descendant Employee:

class Employee : Person
{
    public int salary { get; set; }
}

And second descendant is Guest:

class Guest: Person
{
    public int id { get; set; }
}

Ok! looks good :)

Now I want to display a list of all employees OR guests in a single control ListView

I made a class (it really necessary) for list management PeopleList:

class PeopleList
{
    public List<Person> People { get; set; }

    ...

    public void LoadListFromFile()
    {
        // Load logic

        this.People = new List<?>(source);
    }
}

Do you see this question mark? No? Look at the code again!

How to create an instance of List that I can use my class something like this:

// This instance with the list of Person objects
PeopleList list = new PeopleList();

foreach (Employee e in list.People)
{
    Debug.WriteLine(e.salary.toString());
}

// This instance with the list of Guest objects
PeopleList list = new PeopleList();

foreach (Guest g in list.People)
{
    Debug.WriteLine(g.id.toString());
}

P.S. I'm new in c# and I think that I have a problem in architecture. And maybe you point me to the pattern solves my problem. I really need your help! Thank you!


Solution

  • I think you're after OfType, in the System.Linq library:

    foreach (Employee e in personList.OfType<Employee>())
    {
        Debug.WriteLine(e.salary.toString());
    }
    foreach (Guest g in personList.OfType<Guest>())
    {
        Debug.WriteLine(g.id.toString());
    }