Add to an ICollection

Boardy picture Boardy · Oct 18, 2011 · Viewed 68.8k times · Source

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?

Answer

Donut picture Donut · Oct 18, 2011

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");