Wriju's BLOG

.NET, Cloud and everything

C# 3.0 Enhancements: Extension Methods

Extension Methods are different way of implementing static method. In C# 3.0 it allows us to extend any type and add method for that type. While writing extension method you need to


Ø       declare a public static method


Ø       the first parameter of that method should be the type of the object


Ø       this” keyword has to be the first part of the first argument of that method


 


This helps us to extend methods for the types that are already part of .NET Framework.


 


If you have declared an Extension Method like


 


public static void Foo(this string sVal)


{


    //Do something


}


 


If you make a call to this method the syntax will look like,


 


string s = “Something for test”;


s.Foo();


 


The actual call will happen like


myExtensions.Foo(s); Here myExtensions is the static class under which you have defined the Foo method.


 


Another first class treatment of static method in .NET. It allows us to feel the magic as if we are writing CLR code. You can define most of your utility functions in form of extension method and by using the “using” block you can use them in your code behind file.


 


 


The real life example of the extension method may look like,


 


public static class myExtensions


{


    public static string GetString(this string[] arrStr)


    {


        StringBuilder sb = new StringBuilder();


 


        foreach (string s in arrStr)


        {


            if (sb.Length != 0)


                sb.Append(“,”);


               


                sb.Append(s);               


        }


        return sb.ToString();


    }      


}


 


 


class Program


{        


    static void Main(string[] args)


    {


        string[] sTest = new string[]


{ “Wriju”, “Writam”, “Deb”, “Sumitra” };


 


        Console.WriteLine(sTest.GetString());


        Console.ReadKey();


    }                       


}


 


 


Namoskar!!!