Pages

Men

rh

7/01/2012

How Do We Create Extension Methods in C#

How Do We Create Extension Methods?

The basic outline of creating extension methods goes something like this:
  1. Create a public static class (module in VB) 
  2. Define functions that you wish to perform
  3. Make the functions an extension method
public static class Extensions
{
 
}
The next phase would be to write the function that we are going to need, which in this case is the following:
 
public static class Extensions
{
    public string GetFirstThreeCharacters(String str)
    {
        if(str.Length < 3)
        {
            return str;
        }
        else
        {
            return str.Substring(0,3);
        }
    }
}

To make our C# version of our function, we need an extension method to mark the function as static (so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source. See the following:
public static class Extensions
{
   String str = "my new String";
   str = str.GetFirstThreeCharacters();
 
    public static string GetFirstThreeCharacters(this String str)
    {
        if(str.Length < 3)
        {
            return str;
        }
        else
        {
            return str.Substring(0,3);
        }
    }
}
 
 
Benefits of extension methods
  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
  • If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
  • This feature is important for all developers especially if you would like to use the dynamism of the C# enhancements to be taken place in your classes design. 
    Example:

     

    using System;
    using System.Text;

    namespace ExtensionMethod2
    {
        public static class ExtMetClass
        {
            public static int IntegerExtension(this string str)
            {
                return Int32.Parse(str);
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                string str = "123456";
                int num = str.IntegerExtension();
                Console.WriteLine("The output using extension method: {0}", num);
                Console.ReadLine();
            }
        }
    }

    In the above program we have used extension method IntegerExtension() to convert string to numeric type

    Important points while using extension methods:
  • An extension method must be defined in a top-level static class.
  • An extension method with the same name and signature as an instance method will not be called.
  • Extension methods cannot be used to override existing methods.
  • The concept of extension methods cannot be applied to fields, properties or events.
  • Overuse of extension methods is not good style of programming.

1 comment :