Extension Methods in C#

This article explains Extension Methods in C#. Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

C# extension methods allows developers to extend functionality of an existing type without  without creating a new derived type, recompiling, or otherwise modifying the original type. C# extension method is a special kind of static method that is called as if it was an instance methods on the extended type. In this article, we will create a class library and we will then extend its functionality from the caller code by implementing extension methods. 

C# Extension Method


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 Class Library


Create a project Class Library project in Visual Studio.

extMetLib.gif 
 
Add the following code to the Class1. Class1 has two methods, Display and Print.  
  1. using System;  
  2. using System.Text;  
  3.   
  4. namespace ClassLibExtMethod  
  5. {  
  6.     public class Class1  
  7.     {  
  8.         public string Display()  
  9.         {  
  10.             return ("I m in Display");  
  11.         }  
  12.   
  13.         public string Print()  
  14.         {  
  15.             return ("I m in Print");  
  16.         }  
  17.     }  
  18. }  

Create a Caller Application

Now create a console application in Visual Studio using New Project. Select File > New > Project and select Visual C# and Console Application as shown below.

extMetProject.gif

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

addRefLib.gif

Use the following code and use the ClassLibExtMEthod.dll in your namespace:

  1. using System;  
  2. using System.Text;  
  3. using ClassLibExtMethod;  
  4.   
  5. namespace ExtensionMethod1  
  6. {  
  7.     public static class XX  
  8.     {  
  9.          public static void NewMethod(this Class1 ob)  
  10.         {  
  11.             Console.WriteLine("Hello I m extended method");  
  12.         }  
  13.     }  
  14.   
  15.     class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             Class1 ob = new Class1();  
  20.             ob.Display();  
  21.             ob.Print();  
  22.             ob.NewMethod();  
  23.             Console.ReadKey();  
  24.         }  
  25.     }  
  26. }  
In the above code, you see there is a static class XX with a method, NewMethod. If you notice, the NewMethod takes Class1 as a parameter. This is how you extend an existing library and add your own methods to it. Now, this New Method is available via the class library.
 
When you use Visual Studio Intellisense, you can see the extension method is represented with an arrow (different from the normal method sign), since they were instance methods on the extended type. See the figure below:

extensionMethod.gif

Output of the preceding program looks like the following.

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, 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.
More code snippets of extension expansion methods
  1. using System;  
  2. using System.Text;  
  3.   
  4. namespace ExtensionMethod2  
  5. {  
  6.     public static class ExtMetClass  
  7.     {  
  8.         public static int IntegerExtension(this string str)  
  9.         {  
  10.             return Int32.Parse(str);  
  11.         }  
  12.     }  
  13.   
  14.     class Program  
  15.     {  
  16.         static void Main(string[] args)  
  17.         {  
  18.             string str = "123456";  
  19.             int num = str.IntegerExtension();  
  20.             Console.WriteLine("The output using extension method: {0}", num);  
  21.             Console.ReadLine();  
  22.         }  
  23.     }  
  24. }  
In the preceding program we have used an extension method IntegerExtension() to convert a string to a numeric type.

Important points for the use of 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 a good style of programming.

Conclusion


I hope this article will help you to understand Extension Methods in C# 3.0 and above. If you want to learn more about Extension methods, here is another use case: Create and Use an Extension Method in C#