Extension Methods in C#

An extension method is a feature that adds the capability of adding methods to an existing class without altering or creating a new class. They allow extending the functionality of existing types, for example add a new method to the "string" type. Now let's first see it working.

I want to add a meaningless method to a string type that will return the greetings (array of strings) to the passed string. So if I pass "ram" then it should return an array as follows.

  • Hello ram
  • Good Morning ram
  • Good evening ram
  • Good bye! ram
I also want to control my good morning, evening and bye message using flags, however the Hello message must be returned everytime.

Procedure

  1. Create a static class.
  2. Create the desired method as static in the static class.
  3. Include the namespace of the static class where you want to use it.
  4. Intellisense will list it after every string type variable.
  1. using System;  
  2.   
  3. namespace ConsoleApplication2  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("Enter the name");  
  10.             string name = Convert.ToString(Console.ReadLine());  
  11.             foreach(string str in name.Greeting(true,false,true))  
  12.                 // I want to see default, morning and goodbye. I don't want to say good evening.  
  13.             {  
  14.                 Console.WriteLine(str);  
  15.             }  
  16.             Console.ReadLine();  
  17.         }  
  18.     }  
  19.   
  20.   
  21.     public static class NameAnything // You can name it anything and need not to be any match with the type/class you are adding extension function to.  
  22.     {  
  23.         public static string[] Greeting(this string name, bool isMorningGreeting, bool isEveningGreeting, bool isGoodByeGreeting)  
  24.         {  
  25.             return new string[] { "Hello " + name, isMorningGreeting ? "Good Morning " + name : null, isEveningGreeting ? "Good Evening " + name : null, isGoodByeGreeting ? "Good bye ! " + name : null };  
  26.         }  
  27.     }  
  28. }  
And the output:



Now let us see one more examples of adding extension methods to an existing class. Let us suppose we have our pre-built library of player classes that implement an IPlayer interface as follows.

IPlayer Interface
  1. namespace MyInterface  
  2. {  
  3.     public interface IPlayer  
  4.     {  
  5.         void Play();  
  6.     }  
  7. }  
The following shows MyPlayer classes implementing IPlayer:
  1. using System;  
  2. using MyInterface;  
  3.   
  4. namespace MyPlayers  
  5. {  
  6.     public class Bowler : IPlayer  
  7.     {  
  8.   
  9.         public void Play()  
  10.         {  
  11.             Console.WriteLine("Bowler play method.");  
  12.         }  
  13.     }  
  14.   
  15.     public class Batsman : IPlayer  
  16.     {  
  17.   
  18.         public void Play()  
  19.         {  
  20.             Console.WriteLine("Bastman play method.");  
  21.         }  
  22.         public void Speaks(string str)  
  23.         {  
  24.             Console.WriteLine("Bastman speaks method. Hi " + str);  
  25.         }  
  26.     }  
  27. }  
The Bowler class implements the Play method from an interface whereas the Batsman class defines the additional method Speaks. Over a period of time, you might have added other player classes like Fielder, WicketKeeper, ExtraPlayer, AllRounder and so on implementing only the Play method. You want to add a method "Speaks" to all the classes implementing IPlayer. You should be able to do it by adding the following code.

My extension method:
  1. using System;  
  2.   
  3. namespace MyExtensions  
  4. {  
  5.     using MyInterface;  
  6.     public static class GiveAnyName  
  7.     {  
  8.         public static void Speaks(this IPlayer ip, string name)  
  9.         {  
  10.             Console.WriteLine("Extension speaks method : Hi " + name);  
  11.         }  
  12.   
  13.         public static void Play(IPlayer ip)  
  14.         {  
  15.             Console.WriteLine("Play extension method.");  
  16.         }  
  17.     }  
  18. }  
Now this is how you can call the extension method.
  1. using System;  
  2.   
  3. namespace MyApplication  
  4. {  
  5.     using MyExtensions;  
  6.     using MyPlayers;  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             Bowler bowler = new Bowler();  
  12.             Batsman batsman = new Batsman();  
  13.   
  14.             bowler.Play();  
  15.             bowler.Speaks("Sunil");  
  16.   
  17.             batsman.Play();  
  18.             batsman.Speaks("Sachin");  
  19.   
  20.             Console.ReadLine();  
  21.         }  
  22.     }  
  23.   
  24. }  
So there is no difference between consuming class methods and extension methods. Wait! Let us see the result.



Arrgh! The result seems a bit strange for the Bowler class. It calls an extension method whereas for Batsman it calls the method defined in the class. So why is it like that? It is because at compile time, extension methods always have a lower priority than instance methods defined in the type itself. If you are coming from a JavaScript programming background then you can quickly correlate it with a prototype property of a function.  So you can't use extension methods to override the class.

Extension methods can only be brought into the scope of the namespace. If the namespace is not included, the extension method will not be available.

Though extension methods add power you are less likely to implement it. Having said so, you are definitely going to use extension methods in any real project when you use LINQ. LINQ leverages the power of extension methods to IEnumerable and IQuerable types.


Similar Articles