Blurring the Lines: C# Extension Methods

by bob on April 5, 2007

Here’s another reason why any debates about static vs dynamic languages, prototype vs inheratance based OOP, and so on, are getting increasingly irrelevant. Microsoft is determined to be all things to all developers and seems to be succeeding for the most part without creating some kind of Frankenstien monster.

As evidence, I commend my readers to this excellent and concise explanation of C# 3.0’s new “extenstion methods” feature. Here’s a static, early-bound, strongly-typed, bondage-and-discipline language that lets you effectively add methods to existing classes at will, by simply importing a namespace that has methods that implement a slight syntax twist to associate the method signature with the class they will become a “part” of. The client code looks something like this for an extention to System.Int32 that lives in the MySystemExtensions namespace:

using MySystemExtensions;

...

int i = 5;

Console.Writeline(i.IsEven());

The only potential trouble I see here is that this Intellisense-functional enhancement may confuse people as to what is guaranteed to be available from (say) System.Int32 vs what’s been extended; and where those extensions live. You’ll have to be a bit careful about relying on extensions being available in any arbitrary code base. And be sure to define all extensions in a namespace different from the class you’re extending; that way consumers are forced to place deliberate “using” statements into their code (and perhaps add a project or DLL reference to the solution) in order to invoke them.

C# extension methods are only a first stab; there are no extension properties or events, and extension methods must be defined as static, within a static class (even though they are called as if they are instance methods). But along with LINQ, extension methods are indicative of a trend in C# towards offering at least some key functionality and convenience of dynamic languages.

{ 1 comment… read it below or add one }

Dave August 23, 2007 at 6:41 am

As with all projects. If you use or create components you have to supply them with your application assembly. Same with extentions to common types. In this case you also have to ship the MySystemExtentions.dll assembly.

Extentions only live in the compiler (and IDE). The compiler changes i.IsEven() to MySystemExtention.Int32.IsEven(i), which makes that it can also run on .net 2.0 systems (with in mind that other techniques of 3.0 aren’t used).

Leave a Comment

Previous post:

Next post: