I've got to admit that the first time I hear about Extension Methods, there was something I didn't like about them. It was my linguistics class earlier this year, that actually helped me get over my initial trepidation - extension methods are a grammar change, not a change to semantics. Encapsulation and information hiding still works. With extension methods, you are just changing the word order form Method-Argument to Argument-Method.
Anyway, Scott Bellware posted on using extension methods to implement a specification language:
With RSpec in Ruby, I could code a specification (test) that looks like:
user.username.should_equal "username"
With NSpec in C# 2.0, I would code the same specification as:
Specify.That(user.Username).ShouldEqual("username")
With C# 3.0, using an extension method created specifically for NSpec, the same specification could be coded as:
user.Username.ShouldEqual("username")
Just to be clear, the Username property in C# is an instance of System.String. The extension method doesn't really add new behaviors to the String class directly, but it does allow for an arguably better DSL for NSpec by making use of this new feature in the C# 3.0 compiler.
This is one of the cooler examples of how one could use extension methods to make code more readable. I really dig this and can't wait for C# 3.0.
Source: A Ruby-like Mixin for NSpec Using C# 3.0 Extension Methods
Originally published on Wed, 13 Sep 2006 05:29:00 GMT