ARTICLE

C# Extension Methods

Posted by Puran Mehra Articles | C# Language August 31, 2009
In this article I will explain you about extension methods new feature in C# 3.0 and how to user it.
Reader Level:


What are extension methods?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

How to use extension methods?

An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Program to show how to use extension methods

Create a project Class Library as:

extMetLib.gif

using System;
using
System.Text;

namespace
ClassLibExtMethod
{
    public class
Class1
    {
        public string Display()
        {
            return ("I m in Display");
        }

        public string Print()
        {
            return ("I m in Print");
        }
    }
}


Now create a new project File -> New -> Project

extMetProject.gif

Add the reference of the previously created class library in this project.

addRefLib.gif

Code as following and use the ClassLibExtMEthod.dll in your namespace:

using System;
using
System.Text;
using
ClassLibExtMethod;

namespace
ExtensionMethod1
{
    public static class XX
    {
         public static void NewMethod(this Class1 ob)
        {
            Console.WriteLine("Hello I m extended method");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1 ob = new Class1();
            ob.Display();
            ob.Print();
            ob.NewMethod();
            Console.ReadKey();
        }
    }
}


You can see the extension method with an arrow (different from normal method sign), as they were instance methods on the extended type. See the figure below:

extensionMethod.gif

Output of the above program

extensionMethod1.gif

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.
More Code Snippet to extension expansion methods

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.
Conclusion

I hope that this article would have helped you in understanding Extension Methods in C# 3.0 onwards.

Your feedback and constructive contributions are welcome. Please feel free to contact me for feedback or comments you may have about this article.

Login to add your contents and source code to this article
post comment
     

Great article. It is very useful. Thank you for posting this article.

Posted by Mahesh Alle Mar 15, 2013

Very clear and explained each step with relevant points, well organized steps...well done

Posted by santhosh iype Jan 21, 2012

Short and Sweet

Posted by jayasuthan Jul 15, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter