Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to an ICollection

Tags:

I am currently writing a C# project and I need to do unit testing for the project. For one of the methods that I need to unit test I make use of an ICollection which is normally populated from the selected items of a list box.

When I create a unit test for the method it creates the line

ICollection icollection = null; //Initialise to an appropriate value 

How can I create an instance of this ICollection and an item to the collection?

like image 219
Boardy Avatar asked Oct 18 '11 14:10

Boardy


People also ask

How do I add something to ICollection?

Method 1: ICollection<string> ids = new List<string>(); Method 2: List<string> ids = new List<string>(); First of all: You create the same object, a List<string> in both cases.

What is ICollection in C#?

The ICollection interface is the base interface for classes in the System. Collections namespace. Its generic equivalent is the System. Collections. Generic.

What is the difference between ICollection and IEnumerable?

An ICollection is another type of collection, which derives from IEnumerable and extends it's functionality to modify (Add or Update or Remove) data. ICollection also holds the count of elements in it and we does not need to iterate over all elements to get total number of elements.

Is List an ICollection?

List is the concrete class. This class implements IList, ICollection, IEnumerable.


1 Answers

ICollection is an interface, you can't instantiate it directly. You'll need to instantiate a class that implements ICollection; for example, List<T>. Also, the ICollection interface doesn't have an Add method -- you'll need something that implements IList or IList<T> for that.

Example:

List<object> icollection = new List<object>(); icollection.Add("your item here"); 
like image 188
Donut Avatar answered Sep 28 '22 11:09

Donut