Extension Methods: More than Sugar
One of the enhancements in C# 3.0 is extension methods. Extension methods let you write static functions that look like they belong to other objects - even objects that you didn't write.
Some bloggers have criticised extension methods, saying that they're just syntactic sugar. Yes, they are syntactic sugar; but they're not just syntactic sugar.
Consider this extension method:
Compile t.Foo() as Extender.Foo(t) unless class Thing defines its own method Foo(), in which case you should call that instead.
That's an interesting concept - but there's a problem in Microsoft's proposed implementation. I'll write about it in my next post...
Some bloggers have criticised extension methods, saying that they're just syntactic sugar. Yes, they are syntactic sugar; but they're not just syntactic sugar.
Consider this extension method:
It tells the compiler to act as if the method Foo exists on class Thing:
public static class Extender
{
public static void Foo(this Thing t)
{
//...
}
}
But, that's not all the extension method means. It really means this:
Thing t = new Thing();
t.Foo(); // A - what we write
Extender.Foo(t); // B - what the
//compiler compiles
Compile t.Foo() as Extender.Foo(t) unless class Thing defines its own method Foo(), in which case you should call that instead.
That's what makes extension methods more than just syntactic sugar. They allow you to create a "standard" implemenation of Foo, which is used by all objects except those that define their own specialised implementation instead.
// When we write
t.Foo();
// It compiles the same as this:
Extender.Foo(t);
// unless t.Foo() exists,
// in which case if compiles
// to this, just as if the
//extension method never existed:
t.Foo();
That's an interesting concept - but there's a problem in Microsoft's proposed implementation. I'll write about it in my next post...

2 Comments:
Hi John,
As I mentioned in my post[1], the problem is the methods are *resolved* at compile time.
Suppose you had this:
void DoStuff(this IFoo foo);
class FooFactory
IFoo Create()
If your factory returns an object that provides it's own instance implementation of DoStuff, it will not be invoked - the extension method will instead.
http://www.paulstovell.net/blog/index.php/interface-methods-versus-extension-methods/
Good point. Followup posted here http://dotnet.agilekiwi.com/blog/2008/01/resolving-extension-methods.html and (briefly) to your blog.
Post a Comment
Links to this post:
Create a Link
<< Home