Friday, July 3, 2015

C# in Nutshell Chapter 7 - Collections

Enumerator and Enumerable

IEnumerable can be thought of as “IEnumeratorProvider”
string s = "Hello";
// Because string implements IEnumerable, we can call GetEnumerator():
IEnumerator rator = s.GetEnumerator();
while (rator.MoveNext())
{
char c = (char) rator.Current;
Console.Write (c + ".");
}
// Output: H.e.l.l.o.

Fortunately, you rarely need to write this sort of code, thanks to the foreach statement.


IEnumerable<T> (and IEnumerable)
Provides minimum functionality (enumeration only)

ICollection<T> (and ICollection)
Provides medium functionality (e.g., the Count property)

IList <T>/IDictionary <K,V> and their nongeneric versions
Provide maximum functionality (including “random” access by index/key)


ICollection<T> and ICollection

ICollection<T> is the standard interface for countable collections of objects. 

It provides the ability to determine the size of a collection (Count), determine whether an item exists in the collection (Contains), copy the collection into an array (ToArray), and determine whether the collection is read-only (IsReadOnly). For writable collections, you can also Add, Remove, and Clear items from the collection. And since it extends IEnumerable<T>, it can also be traversed via the foreach statement.

The nongeneric ICollection is similar in providing a countable collection, but doesn’t provide functionality for altering the list or checking for element membership:


IList<T> and IList

IList<T> is the standard interface for collections indexable by position.

In addition to the functionality inherited from ICollection<T> and IEnumerable<T>, it provides the ability to read or write an element by position (via an indexer) and insert/remove by position:

IReadOnlyList<T>

In order to interoperate with read-only Windows Runtime collections, Framework 4.5 introduces a new collection interface called IReadOnlyList<T>.











































No comments:

Post a Comment