Hi,@兰树豪. Welcome Microsoft Q&A.
Yes, "ICollection" is a type. You could use an interface declaration and instantiate it with a class that implements the interface.
The ICollection<T> interface is the base interface for classes in the System.Collections.Generic
namespace.
The ICollection<T>
interface extends IEnumerable<T>
and is extended by IDictionary<TKey, TValue>
and IList<T>
.
There are two rules I follow:
Accept the most basic type that will work
Return the richest type your user will need
So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.
On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.