Extention Methods are a very useful tool we just got in C# 3.0. We could define them as static methods that extend existing classes, Even System classes!!!
If we wanted to do something like that in the past we had to derive from the selected class and extend it with whatever we wanted. But what if that class was sealed? If that was the case we were in a jam. Extention methods come in just for that. No more deriving classes just to add a simple method we need, and of course no more implementing MyInt (I know some who did) classes or similar… :)

Lets see how its done.

Lets say we need to reverse a string. Before we had extention methods we would probably have something like this:

public class StringOperations
    {
        public static string ReverseString(string str)
        {
            string i = string.Empty;   

            foreach (char c in str)
            {
                i = i.Insert(0, c.ToString());
            }
            return i;
        }
    }

And we would use it like this:

static void Main(string[] args)
{
       string g = StringOperations.ReverseString("abcd");
}

Well now we don’t have to. We can actually attach the ReversString method to the string object! Here’s how:

namespace System
{
    public static class Extentions
    {
        //notice that we use this as the parameter.
        public static string Reverse(this string str)
        {
            string i = string.Empty;   

            foreach (char c in str)
            {
                i = i.Insert(0, c.ToString());
            }
            return i;
        }
    }
}

We have just extended the System namespace with a method called Reverse.  Hurray!

Now we can reverse a string like this:

string gg  = ("abcd").Reverse();

How nice is that?

Subscribe to our feed and get the complete code sample for this article

Enjoy

Amit

Tags :

Post a Comment