Search code examples
c#.netgeneric-collections

How can a list with one member be useful?


I read an SO which asked for the easiest way to create a list with a one member.

Quick way to turn object into single-element list?

This raised a question for me, when would this be useful?

I can't think of an example when I would use a List<T> with a single member over just the T variable itself.

Can someone explain or provide an example?


Solution

  • In general, this happens when you have a logical collection of elements that just happens to contain one member. For example, you might have a House class with a collection of Room items, but the OneRoomSchoolhouse class only has one object in its Rooms collection.

    As another example, you might have a method with this signature:

    void LogNewItems(List<Item> newItems);
    

    If you have only one item, you would have to pass it thus:

    LogNewItems(new List<Item> { item });
    

    In fact, if you're designing the item-logging API, you might create a convenience method so developers don't have to do that. The method could look something like this:

    void LogNewItem(Item item)
    {
        LogNewItems(new List<Item> { item });
    }