Search code examples
c#genericscollections

Why using 'ICollection<T>'?


I'm an inexperienced C# hobbyists who tries to learn a bit of c# when I have a little bit of time left, like now lately.

I'm trying to figure out when to use ICollection<T>.

I have searched on YouTube and online documentation. But they cover "how to use it", not why and when to use it. For example a title like below would be far more helpful to me:

"Hey, are you always using List<T>? Find out how ICollection<T> could be more helpful!"

Nothing seems to be out there. I assume one has to learn this in some indirect way. Either way, can anyone provide and answer and even perhaps an example why one would use this, instead of one of lists, arrays and whatnot?

Edit: I don't even know how to ask a question because I don't know what I'm talking about. Here's the code which triggered my interest:

ICollection<ValidationResult> validationResultList = new List<ValidationResult>();

What is happening here?


Solution

  • The simple answer is, use ICollection<T> when you need something more abstract than List<T> (or other collection, such as HashSet<T>).

    You use the interface because you may not care about receiving List specifically. You care about receiving an object that implements the methods contracted by the interface. You just want to know that when something is passed into your method, and you then call myArgument.neededMethod(), that you know for certain that this method will have been implemented.