CHAPTER 9 COLLECTIONS AND GENERICS
Action for this event: Add
Here are the NEW items:
Name: Fred Smith, Age: 32
Action for this event: Remove
Here are the OLD items:
Name: Peter Murphy, Age: 52
That wraps up our examination of the various collection-centric namespaces in the .NET base class
libraries. To conclude our chapter, we will now examine how we can bu ild our own custom generic
methods and custom generic types.
Source Code You can find the FunWithObservableCollection project under the Chapter 9 subdirectory.
Creating Custom Generic Methods
While most developers typically use the existing generic types within the base class libraries, it is also
possible to build your own generic members and custom generic types. Let’s look at how to incorporate
custom generics into your own projects. The first step is to build a generic swap method. Begin by
creating a new console application named CustomGenericMethods.
When you build custom generic methods, you achieve a supercharged version of traditional method
overloading. In Chapter 2, you learned that overloading is the act of defining multiple versions of a single
method, which differ by the number of, or type of, parameters.
While overloading is a useful feature in an object-oriented language, one problem is that you can
easily end up with a ton of methods that essentially do the same thing. For example, assume you need to
build some methods that can switch two pieces of data using a simple swap routine. You might begin by
authoring a new method that can operate on integers, like this:
// Swap two integers.
static void Swap(ref int a, ref int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
So far, so good. But now assume you also need to swap two Person objects; this would require
authoring a new version of Swap():
// Swap two Person objects.
static void Swap(ref Person a, ref Person b)
{
Person temp;
temp = a;
a = b;
349