Collection<T> | Provides the base class for a generic collection. |
KeyedCollection<TKey, TItem> | Provides the abstract base class for a collection whose keys are embedded in the values. |
ObservableCollection<T> | Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed. |
ReadOnlyCollection<T> | Provides the base class for a generic read-only collection. |
ReadOnlyObservableCollection<T> | Represents a read-only ObservableCollection<T>. |
Let's take a look at Collection<T>, one of the classes available. It is similar to the generic List<T> class. Both Collection<T> and List<T> implement the IList<T> and ICollection<T> interfaces. The main difference between the two is that Collection<T> contains virtual methods that can be overridden, whereas List<T> does not have any.
The List<T> generic class is discussed in details in Chapter 13.
The following code example shows how to use the generic Collection<T> class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CollectionEg1 {
class Program {
static void Main(string[] args) {
foreach (string name in names) {
Console.WriteLine(name);
}
Console.ReadLine();
}
}
}
Here's the example's output:
Johnny
Michael
Wellington
To understand the usefulness of the generic Collection<T> class, consider the following example where you need to write a class to contain the names of all the branches a company has:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace CollectionEg2 {
class Program {
static void Main(string[] args) {}
}
}
In this example, the Branch class exposes a public read-only property called BranchNames of type List<T>. To add branch names to a Branch object, you first create an instance of the Branch class and then add individual branch names to the BranchNames property by using the Add() method of the List<T> class:
static void Main(string[] args) {
}
Suppose now that your customers request an event for the Branch class so that every time a branch name is deleted, the event fires so that the client of Branch class can be notified. The problem with the generic List<T> class is that there is no way you can be informed when an item is removed.
A better way to resolve this issue is to expose BranchName as a property of type Collection<T> instead of List<T>. That's because the generic Collection<T> type provides four overridable methods — ClearItems(), InsertItem(), RemoveItem(), and SetItem() — which allow a derived class to be notified when a collection has been modified.
Here's how rewriting the Branch class, using the generic
