Skip to content

SingleItem

Pawel Gerr edited this page Apr 29, 2025 · 2 revisions

SingleItem (collections)

Resource-saving alternative for creation of a collection with 1 item only.

// We have 2 overloads of a method. One with 1 item only, and the the other using a collection.
// The one should call the other to prevent implementing the method twice.
public void Do(IReadOnlySet<string> names)
{
    // implemention
}

public void Do(string name)
{
    // Delegates the call to other overload.

    IReadOnlySet<string> names = SingleItem.Set(name);
    
    Do(names);
}

------------

IReadOnlyDictionary<int, string> dictionary = SingleItem.Dictionary(42, "name");

ILookup<int, string> lookup = SingleItem.Lookup(42, new[] { "name", "other name" });

IReadOnlySet<int> set = SingleItem.Set("name");
Clone this wiki locally