Extension Methods "Hello World" I: Introduction

I decided that it's about time to famil­iar­ize myself with new fea­tures 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 under­stand­ing of all those new good­ies that new ver­sion of framework/language brings. What I mean by famil­iar­ize is under­stand thor­oughly and that is what this "Hello World" series (hope­fully) is (hope­fully) about.

I'm gonna start with exten­sion meth­ods as this is what I've started play­ing with already, and then… well we'll see :)

Exten­sion Meth­ods are a com­pletely new con­cept to OOP world (at least from what I know), and they may seem odd to peo­ple with strong OOP back­ground. We're used to, that in order to extend a class with new behav­ior we inherit a new class from it, and add meth­ods to this inher­ited class. Plain and sim­ple. But how about, for exam­ple, sealed classes? Let's take a basic exam­ple: You want to be able to alter a string to have first let­ter in each world capitalized.

To accom­plish this you would prob­a­bly want to do some­thing like:

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

Plain and sim­ple, isn't it? Unfor­tu­nately this code has one flaw: It won't com­pile. System.String is marked as sealed, so you can't inherit from it. The only option you have left is to del­e­gate this work to some other class, for exam­ple 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 com­pile, 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 some­thing 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 accom­plish the goal, but you have to explic­itly call another class's method, so of makes your code more dif­fi­cult to use.

This is one of pos­si­ble places where you might want to use Exten­sion Method. As most new things in C# 3.0 (and VB9.0, or Chrome 2.0 for that mat­ter), Exten­sion Meth­ods we're intro­duced to enable LINQ. They basi­cally are a syn­tac­tic sugar, but they can greatly improve read­abil­ity of your code, and make it eas­ier to use, like in this example.

Using Exten­sion method you can pin meth­ods to classes you don't con­trol (like System.String), so that although imple­men­ta­tion of the method is con­tained in some cus­tom class, you can call the method as if it was imple­mented by System.String.

Using Exten­sion Meth­ods in its core is plain and sim­ple. You cre­ate a  sta­tic class with sta­tic method, where first para­me­ter is of type you want to extend, pre­ceded by key­word 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 lit­tle cos­metic change you can call our new method directly on type string. It is con­ve­nient for users of your code, as they will see this method in their Intel­liSence drop­down. Notice that it has dif­fer­ent icon, with lit­tle drop­ping arrow, that will enable you to imme­di­ately dis­tin­guish Exten­sion Meth­ods from other. ExtensionMethodsHelloWorldPartI

In Part II we will take a closer look at how com­piler decides which of sev­eral can­di­date exten­sion meth­ods to call.

  • http://www.mezzastudio.co.uk/adam Adam Mar­gi­son

    Nice Hello World for Exten­sion Methods!

    They're not a com­pletely new con­cept in the OOP world though — as far as I can see, they're an imple­men­ta­tion of the dec­o­ra­tor design pattern.

    Very use­ful though — thanks for posting.