Jul 10, 2015

Extension Method In C#

Extension methods are a new feature in C# 3.0. An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. We can say that it extends the functionality of an existing type in .NET. An extension method is a static method to the existing static class. We call an extension method in the same general way; there is no difference in calling.

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.


Create a project Class Library as:

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 using "File" -> "New" -> "Project...".

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

Use the following code 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();
        }
    }
}



 Output of the preceding program


 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, in other words extension methods.
  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.

 

No comments:

Post a Comment