So, many times we have a function that accepts an IEnumerable or ICollection as a parameter. In cases where we have single items, but no collection to hold them, we must create a collection before passing them to the function, like:
T o1, o2, o3;
Foo(new T[] { o1, o2, o3 });
I've always created an array or a list, like I've done in the last example. But I wonder, is there a more elegant way to create the required IEnumerable or ICollection?
It would be quite cool, if one could do this:
Foo({ o1, o2, o3 });
And the compiler would create the most abstract possible collection that would satisfy the needs of IEnumerable or ICollection (depending on which one the function accepts).
Anyhow, how you would pass o1, o2 and o3 to an IEnumerable or ICollection parameters?
IEnumerable contains only GetEnumerator() method, like read-only iterate. ICollection is one step ahead of IEnumerable. If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable.
IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator, which returns an IEnumerator<T> object. The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property.
ICollection<T> is an interface that exposes collection semantics such as Add() , Remove() , and Count . Collection<T> is a concrete implementation of the ICollection<T> interface. IList<T> is essentially an ICollection<T> with random order-based access.
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.
The current version of C# (3) supports a notation without explicit type, i.e.
Foo(new [] { o1, o2, o3 })
to create an array. There’s also Linq’s Enumerable.Range
to create a continuous range of numbers. Everything else has to be implemented. In the spirit of Java:
public static IEnumerable<T> AsList<T>(params T[] values) {
return values;
}
to be called like this:
Foo(Enumerable.AsList(o1, o2, o3));
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