CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
}
}
}
Given that the PrintDataAndBeep() method can be used by any class or structure that implements
IEnumerable, we could test via the following Main() method:
static void Main( string[] args )
{
Console.WriteLine("***** Extending Interface Compatible Types *****\n");
// System.Array implements IEnumerable!
string[] data = { "Wow", "this", "is", "sort", "of", "annoying",
"but", "in", "a", "weird", "way", "fun!"};
data.PrintDataAndBeep();
Console.WriteLine();
// List implements IEnumerable!
List myInts = new List() {10, 15, 20};
myInts.PrintDataAndBeep();
}
Console.ReadLine();
That wraps up our examination of C# extension methods. Remember that this particular language
feature can be very useful whenever you want to extend the functionality of a type, but do not want to
subclass (or can not subclass if the type is sealed), for the purposes of polymorphism. As you will see
later in the text, extension methods play a key role for LINQ APIs. In fact, you will see that under the
LINQ APIs, one of the most common items being extended is a class or structure implementing
(surprise!) the generic version of IEnumerable.
Source Code The InterfaceExtension project can be found under the Chapter 11 subdirectory.
Understanding Anonymous Types
As an OO programmer, you know the benefits of defining classes to represent the state and functionality
of a given item you are attempting to model. To be sure, whenever you need to define a class that is
intended to be reused across projects and provides numerous bits of functionality through a set of
methods, events, properties, and custom constructors, creating a new C# class is common practice.
However, there are other times when you would like to define a class simply to model a set of
encapsulated (and somehow related) data points without any associated methods, events, or other
specialized functionality. Furthermore, what if this type is to be used only by a handful of methods in
your program? It would be rather a bother to define a full class definition as shown below; when you
know full well this class will be used only in a handful of places. To accentuate this point, here is the
rough outline of what you might need to do when you need to create a “simple” data type that follows
typical value-based semantics:
423