Free mag vol1 | Page 482

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES Figure 11-1. The IntelliSense of extension methods Any method marked with this visual icon is a friendly reminder that the method is defined outside of the original class definition via an extension method.  Source Code The ExtensionMethods project can be found under the Chapter 11 subdirectory. Extending Types Implementing Specific Interfaces At this point, you have seen how to extend classes (and, indirectly, structures that follow the same syntax) with new functionality via extension methods. It is also possible to define an extension method that can only extend a class or structure that implements the correct interface. For example, you could say something to the effect of “if a class or structure implements IEnumerable, then that type gets the following new members.” Of course, it is possible to demand that a type support any interface at all, including your own custom interfaces. To illustrate, create a new Console Application named InterfaceExtensions. The goal here is to add a new method to any type that implements IEnumerable, which would include any array and many nongeneric collection classes (recall from Chapter 8 that the generic IEnumerable interface extends the nongeneric IEnumerable interface). Add the following extension class to your new project: static class AnnoyingExtensions { public static void PrintDataAndBeep(this System.Collections.IEnumerable iterator) { foreach (var item in iterator) { Console.WriteLine(item); Console.Beep(); 422