Interfaces + Extension Methods = POWER

I spoke recently at Dallas Code Camp 2 about C# 3.0 and the new language features it contains.  Most of the buzz on the net has been about LINQ, understandably, but as I've mentioned here before I really, really, dig extension methods.  I've spent a good bit of time thinking about uses for them, and looking at how Microsoft has used them in .NET 3.5.

One of the things that didn't click the first time I played with extension methods which you might have missed to is that you do not have to extend classes, you can extend interfaces.  Think about that a moment, you can write methods, with functionality, that act upon interfaces.

For example I've previously spoken here about the Model View Presenter pattern, which is normally implemented with an Interface (The View), a Data Access Object (The Model), and a class to map between them (The Presenter).  "The Presenter" takes "The View" in it's constructor and simply acts upon "The View" in it's methods.  "The View" is implemented as an interface because you can have multiple interfaces, but this requires another class for "The Presenter" because interfaces can't contain any code.  Until Now.

With extension methods it becomes perfectly possible to forgo the need for a Presenter class in favor of a set of extension methods.  Does this save typing?  No, in all likelihood you've not save many keystrokes when writing your Presenter but you have gotten rid of the need to ever declare the Presenter on your pages/forms at all.  If you implement IDisplayBlogPost on your ASP.NET page, then if you extend that interface with a method called "public static GetBlogPostByTitle(this IDisplayBlogPost view, string title)" then your page now has that method itself, and a simple "this.GetBlogPostByTitle(blogTitle);" can result in population of your page.

This essentially brings to .NET the power of Multiple Inheritance without the problems with Multiple Inheritance that exist in certain other languages.

I'm still downloading Beta 1 of Orcas, but rest assured code samples for this are coming.