What's hot ? (and I mean really ...) - scroll down for more
1).  Code Templating - advanced usage of delegates & generics: my slides & demos are available for download! CodeProject article is also available.

2).  My series "TDD in the eyes of a simpleminded" is in progress(including code!): preface, part1, part2, Q&A 1, Manual Stub .vs. Mock Stub

3).  TDD Workshop: SeeCompass v0.1 and v0.2 are out.
# Wednesday, April 04, 2007

One of my favorite C# 3.0 features is Extension Methods. In short, it ables you to extend an existing type with additional behaviors. For example, you can consider to extend the type System.Int32 (aka "int") with a new method named IsEven.

The syntax is quite trivial:

namespace Lnbogen.Extensions
{
    public static class Extentions
    {
        public static bool IsEven(this int i)
        {
            return ((i%2)==0);
        }
    }
}

Notice the "this int" which means "I want to extend the type int".
Now I can write the following code (fully IntelliSense-d and compile time checking):

using Lnbogen.Extensions; //<- this will load the extensions, it won't compile without it!

... void TestIsEven()
{
   int num = 5;
   Console.WriteLine(num.IsEven());
}

What's going on behind the scenes is quite simple, the compiler got a little "smarter" and now knows to look for Extension Methods in the imported namespaces. I don't want to elaborate too much about the syntax and requirements as Anders Hejlsberg makes it all clear in his MSDN video: C# 3.0: Future Directions in Language Innovation.


Let me direct you to the  real  meat:


Extension Methods is going to change the way we enhance "already used" code. Up to now, looking at that need (for backward compatibility), Microsoft suggested to create an interface and an abstract class that implement this interface. This allows us to extend the abstract class simply by providing new virtual members without breaking the code. The problem in this solution is that things were getting out of sync really fast leaving our interfaces shy & dry(=out of date), just to avoid breaking changes. Even worse, due to the fact that multi-inheritance is forbidden, inheriting from the abstract class pretty much slammed the door on most of our design choices. 

Let's face it; Interfaces were programmer's nightmare(before you hack my blog and delete this post, bare with me). On one hand, we're reluctant to implement an interface with 10 members as we prefer to finish our tasks in this century but on the other hand, we want our interface to expose as much API as it can to allow easy usage for its customers(=programmers) and to avoid casting it(the interface) to "specialist" interfaces.

Well, Extension Methods allows us to extend any type. Do you get my drift here?
You can now enhance any interface you've ever exposed thus making old interfaces incredibly strong. You can define a lightweight interface(easy for the implementor of the interface) and extend its abilities without breaking any existing code(enrich the customers of the interface). This is exactly what Microsoft did with LINQ. They have extended IEnumerable<T> with many Query methods such as "Select", "From", "Where", "GroupBy", "Join" (and much more...) to enhance it with a great set of new methods while still keeping the original interface untouched. All we have to do is simply import System.Query namespace.


Brilliant.

.NET | C# 3.0
Tuesday, April 10, 2007 4:58:37 PM (Jerusalem Standard Time, UTC+02:00)
first of all thanks for sharing this intersting new feature.
it should be useful in the near future when i'll start coding in 3.0.

if i understood correctly the work method here then in addition to manging my current types , i'll have to manage an extesion class too. you may keep all your extensions in just one class but as your code will grow you will have to manage sevral extensions classes. plus it will be harder to understand your code because for each type you've extended you'll have to track the specific extension class.

but then again , i might be way off.... : )
Gadi.
Gadi Berqowitz
Friday, April 13, 2007 7:23:17 PM (Jerusalem Standard Time, UTC+02:00)
Gadi this is a great point and a great "fear" of misusing\abusing this feature. Most of the time, this can help you to empower BCL(Micrsoft .net library) types or 3rd parties component (where you don't have the source code availabe). I'm not saying you should add extension methods to your types as a default behavior though it can come handy when you do have the source but you don't want to break your code(usually interfaces).

Like many things in OO programming, splitting responsibilities has its cost, but the trade-off usually worth it - I prefer managing my code structure(namespaces, naming, files location etc) better and use Extension Methods than breaking working code.
Comments are closed.