Chapter 10. Extension methods

This chapter covers

  • Writing extension methods
  • Calling extension methods
  • Method chaining
  • Extension methods in .NET 3.5
  • Other uses for extension methods

I’m not a fan of inheritance. Or rather, I’m not a fan of a number of places where inheritance has been used in code that I’ve maintained, or class libraries I’ve worked with. As with so many things, it’s powerful when used properly, but its design overhead is often overlooked and can become painful over time. It’s sometimes used as a way of adding extra behavior and functionality to a class, even when no real information about the object is being added—where nothing is being specialized.

Sometimes that’s appropriate—if objects of the new type should carry around the details of the extra behavior—but often it’s not. Often it’s just not possible to use inheritance in this way in the first place, such as when you’re working with a value type, a sealed class, or an interface. The alternative is usually to write a bunch of static methods, most of which take an instance of the type in question as at least one of their parameters. This works fine, without the design penalty of inheritance, but it tends to make code look ugly.

10.1. Life before extension methods

10.2. Extension method syntax

10.3. Extension methods in .NET 3.5

10.4. Usage ideas and guidelines

10.5. Summary

sitemap