Another great feature in c# 3.0 is Extension Methods. Extension Methods are created in a way that allow developers to inject them in other classes as being part of them. This article will provide an example of this.

 

As you know, the string type has many methods and the length property. But suppose that, for some reason, you wish string objects to have a new method available, say, to add a timestamp on the start of the string. This is where Extension Methods come in handy. An Extension Method that would allow us to do this, is the following:

 

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 

    6 namespace MyExtenders

    7 {

    8     public static class Extenders

    9     {

   10         public static string ApplyTimestamp(this string text)

   11         {

   12             return DateTime.Now.ToLongTimeString() + " -> " + text;

   13         }

   14     }

   15 }

I've defined my extender method in a namespace chosen by me, called it MyExtenders, and added a class called Extenders to contain it. I've named the extender method ApplyTimestamp(), and what it does is to prefix a string with date and time. Remember this method will be available to a string type object, and so, it will target the string object's value. That's why ApplyTimestamp has the this keyword, and that's what makes this feature pump.

 

Now, for us to be able to use this method in our string objects along our application, we just need to reference the MyExtenders namespace with the using statement, and it will be available in all our string objects:

 

 

This is indeed a nice feature.