Sunday, April 02, 2006

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:
public static class Extender
public static void Foo(this Thing t)
It tells the compiler to act as if the method Foo exists on class Thing:
Thing t = new Thing();
t.Foo();                 // A - what we write
Extender.Foo(t);         // B - what the
//compiler compiles 
But, that's not all the extension method means. It really means this:

Compile t.Foo() as Extender.Foo(t) unless class Thing defines its own method Foo(), in which case you should call that instead.
// When we write

// It compiles the same as this:

// unless t.Foo() exists, 
// in which case if compiles
// to this, just as if the
//extension method never existed:
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.

That's an interesting concept - but there's a problem in Microsoft's proposed implementation. I'll write about it in my next post...


Anonymous paul stovell said...

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.

Mon Jan 14, 05:48:00 AM PST  
Blogger John Rusk said...

Good point. Followup posted here and (briefly) to your blog.

Mon Jan 14, 11:47:00 PM PST  

Links to this post:

Create a Link

<< Home