Search code examples
c#conventions

c# support both multiple and single object operations


Say I have the following methods in my code:

public bool RemoveItem(Item item)
{ 
   // Logic to remove a single item
}

public bool RemoveItems(List<Item> items)
{
   // Logic for removing multiple items. Running over all items and calling RemoveItem will be inefficient in my case
}

public bool AddItem(Item item)
{
  // Logic for adding single item
}

public bool AddItems(List<Item> items)
{
  // Logic for adding multiple items
}

Is there a way to prevent having multiple methods for each operation? I have alot of such methods. I wish to somehow combine each couple of methods into a single one..is there a nice way for doing so?

I can create a list with single item and support only methods that take list as parameter but is seems ugly to me.

How do other people do it?


Solution

  • You can create your methods with params keyword:

    public bool AddItems(params Item[] items)
    {
        ...
    }
    
    public bool RemoveItems(params Item[] items)
    {
       ...
    }
    

    This allows you call these methods like this:

    AddItems(item);
    AddItems(item1, item2, ...);
    or
    AddItems(new Item[] { ... });