C # supports both operations with several and single objects

Let's 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 using multiple methods for each operation? I have many such methods. I want to somehow combine each pair of methods into one. Is there a good way to do this?

I can create a single-element list and only support methods that take the list as a parameter, but it seems ugly to me.

How do other people do it?

+4
source share
3 answers

You can create your methods using the keyword params:

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

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

This allows you to call these methods as follows:

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

. , Add() AddRange()

+4

, , funstion.

0

All Articles