Search code examples
c#listobjectsubclassradix

More objects with different type in one list


Is it possible to add more objects of different types to the same list and how do I do it?

I've got a base class and three subclasses and I want all the subclass objects in the same list.


Solution

  • Sure - just create a list using the base type as the generic type argument:

    List<Control> controls = new List<Control>();
    controls.Add(new TextBox());
    controls.Add(new Label());
    controls.Add(new Button());
    // etc
    

    Note that when you retrieve the items again, you'll only "know" about them as the base type though, so you'll need to cast if you want to perform any subtype-specific operations. For example:

    // Assuming you know that there's at least one entry...
    Control firstControl = controls[0];
    TextBox tb = firstControl as TextBox;
    if (tb != null)
    {
        // Use tb here
    }
    

    If you want to get all the elements of a particular type (or subtype thereof) you can use the OfType<> method:

    foreach (TextBox tb in controls.OfType<TextBox>())
    {
        // Use tb here
    }