Extension Method in C#

Kailash Chandra Behera | Sunday, September 18, 2016

Introduction

This article describes about the new feature Extension Method added int C#3.0 and how it works.

Getting Started

Extension Method is the most favorite feature in .net that Microsoft added in C#3.0. it enables 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. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

The following example shows an extension method defined for the System.String class. It's defined inside a non-nested, non-generic static class:

 namespace ExtensionMethods  
 {  
   public static class MyExtensions  
   {  
     public static string Concatenate(this string str1,string str2)  
     {  
       return str1+" "+str2;  
     }  
   }  
 }  
The extension methods can be brought into scope with this using directive or namespace And it can be called from an application as like below
 using ExtensionMethods;  
 namespace Extensionexample  
 {       
      class program  
      {  
           static void Main()  
           {  
                Student student=new Student();  
                student.FirstName="Nidhi";  
                student.LastName="Behera";  
                Console.WriteLine(student.Concatenate(student.FirstName,student.LastName));  
                Console.ReadLine();  
           }  
      }  
 }  
As alike interface or class method, an Extension method cannot be overloaded and override. An extension method always has a lower priority than instance methods defined in the type itself. In other words, if a type has a method named length(string value), and you have an extension method with the same signature, the compiler will always bind to the instance method.

When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

When we invoke an extension method, the intermediate language (IL) generated by the compiler translates our code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.

To not violate the principle of the encapsulation the intermediate language (IL) generated by the compiler translates our code into a call on the static method when we invoke an extension method and extension methods cannot access private variables in the type they are extending.

The most common extension methods are the LINQ standard query operators(such as GroupBy, OrderBy, Average) which add query functionality to the existing collection, generic collection, list, and array, etc. First, it needs to bring them into scope with a using System. Linq directive, to use the standard query operators.

The below example shows how to call the standard query operator OrderBy method on an array of integers.

 class ExtensionExample    
 {  
   static void Main()  
   {        
     int[] ints = { 1, 5, 15, 9, 2, 6 };  
     var result = ints.OrderBy(g => g);  
     foreach (var i in result)  
     {  
       System.Console.Write(i + " ");  
     }        
   }      
 }  
 //Output: 1 2 5 6 9 15  

Summary

In this article we descussed about the extension method and how it work, hope this artilce may helpful to you.

Thanks