Extension Methods "Hello World" I: Introduction

I decided that it’s about time to familiarize myself with new features of .NET 3.5 and C# 3.0. And I don’t mean see an overview, because I’ve read many times about what’s new in it, and I have basic understanding of all those new goodies that new version of framework/language brings. What I mean by familiarize is understand thoroughly and that is what this “Hello World” series (hopefully) is (hopefully) about.

I’m gonna start with extension methods as this is what I’ve started playing with already, and then… well we’ll see :)

Extension Methods are a completely new concept to OOP world (at least from what I know), and they may seem odd to people with strong OOP background. We’re used to, that in order to extend a class with new behavior we inherit a new class from it, and add methods to this inherited class. Plain and simple. But how about, for example, sealed classes? Let’s take a basic example: You want to be able to alter a string to have first letter in each world capitalized.

To accomplish this you would probably want to do something like:

using System;
public class MyString:String
{
    public string ToFirstCapitalized()
    { 
        //any implementation you'd like (as long as it's black)
    }
}

Plain and simple, isn’t it? Unfortunately this code has one flaw: It won’t compile. System.String is marked as sealed, so you can’t inherit from it. The only option you have left is to delegate this work to some other class, for example like this:

using System;
public static class MyStringCapitalizator
{
    public static string ToFirstCapitalized(string input)
    { 
        //any implementation you'd like (as long as it's black)
    }
}

Well, this at least will compile, although now instead of this:

string someString = "It's SoME weIrD StrING. Isn'T iT? IT BEcamE liKE This FRoM ListTENING to JINGLE from BETTer kNOW a FRAmEwoRK";
string capitalizedString = someString.ToFirstCapitalized();

You have to write something like this:

string someString = "It's SoME weIrD StrING. Isn'T iT? IT BEcamE liKE This FRoM ListTENING to JINGLE from BETTer kNOW a FRAmEwoRK";
string capitalizedString = MyStringCapitalizator.ToFirstCapitalized(someString);

You now are able to accomplish the goal, but you have to explicitly call another class’s method, so of makes your code more difficult to use.

This is one of possible places where you might want to use Extension Method. As most new things in C# 3.0 (and VB9.0, or Chrome 2.0 for that matter), Extension Methods we’re introduced to enable LINQ. They basically are a syntactic sugar, but they can greatly improve readability of your code, and make it easier to use, like in this example.

Using Extension method you can pin methods to classes you don’t control (like System.String), so that although implementation of the method is contained in some custom class, you can call the method as if it was implemented by System.String.

Using Extension Methods in its core is plain and simple. You create a  static class with static method, where first parameter is of type you want to extend, preceded by keyword this.

 

namespace ExtensionMethodsHelloWorldPartI
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string someString =
                "It's SoME weIrD StrING. Isn'T iT? IT BEcamE liKE This FRoM ListTENING to JINGLE from BETTer kNOW a FRAmEwoRK";
            
            //you can call method explicitly
            string capitalizedString1 = MyStringCapitalizator.ToFirstCapitalized(someString);
 
            //or as if it was implemented by System.String
            string capitalizedString2 = someString.ToFirstCapitalized();
        }
    }
    public static class MyStringCapitalizator
    {
        public static string ToFirstCapitalized(this string input)
        {
            //any implementation you'd like (as long as it's black)
        }
    }
}

Thanks to this little cosmetic change you can call our new method directly on type string. It is convenient for users of your code, as they will see this method in their IntelliSence dropdown. Notice that it has different icon, with little dropping arrow, that will enable you to immediately distinguish Extension Methods from other. ExtensionMethodsHelloWorldPartI

In Part II we will take a closer look at how compiler decides which of several candidate extension methods to call.

  • http://www.mezzastudio.co.uk/adam Adam Margison

    Nice Hello World for Extension Methods!

    They’re not a completely new concept in the OOP world though – as far as I can see, they’re an implementation of the decorator design pattern.

    Very useful though – thanks for posting.