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?
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.
The ICollection interface is the base interface for classes in the System. Collections namespace. Its generic equivalent is the System. Collections. Generic.
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.
List is the concrete class. This class implements IList, ICollection, IEnumerable.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With