Scott Guthrie wrote a post on Extension Methods, called New "Orcas" Language Feature: Extension Methods, which used a similar example of Extension Methods I wrote in a post last year, called Extension Methods in C# 3.0 - C# Tutorials and Examples.
I like what Scott says at the end: "Just because you have a shiny new hammer doesn't mean that everything in the world has suddenly become a nail!" Wiser words have never been spoken, but I have never been one to miss an opportunity to goof off and abuse language enhancements
.
I have a fondness for data access and O/R Mappers and thought I would port some of the functionality in my own homegrown O/R Mapper as Extension Methods. I mentioned my ActiveRecord O/R Mapper in a couple of posts which was inspired by Castle Project's ActiveRecord:
Let's take a simple class as follows ( note I am using Automatically Implemented Properties in C# 3.0 ):
[Table("Customers")]
public class Customer : IEntity
{
[Column]
public string CustomerId { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string EmailAddress { get; set; }
}
that defines a class that will be persisted to a Customers Table.
Using Extension Methods in C# 3.0 we can give this class instance a number of new methods that deal with persistence and what have ya via the IEntity Interface
public static class ActiveRecordExtensions
{
public static int Save(this IEntity entity)
{
// Persist...
}
}
As long as these Extension Methods are in scope, we can get a nice set of methods ( in this case I am only showing 1 ) to help with persistence and selection from our persistence store:

In this case my IEntity Interface is nothing but a "filter" so that only a select few of classes have the ActiveRecord Extension Methods. Nothing is defined in the IEntity Interface:
public interface IEntity {}
I explicity said the Save Method will work with classes that implement IEntity:
public static class ActiveRecordExtensions
{
public static int Save(this IEntity entity)
{
// Persist...
}
}
This is definitely a shiny new hammer looking for a nail, but it is rather cool to attach behavior to objects via Extension Methods. It seems we are all suggesting not to abuse the language enhancement, but the tinkerer in me suggests otherwise
.
As an aside, I love the graphical image that denotes Extension Method versus regular methods:

Download the Visual Studio Orcas March 2007 CTP to play with this stuff.
by David Hayden
Posted
03-28-2007 5:33 PM
by
David Hayden