When Should We Use Extension Methods In C#

When we needed to add a new function to an existing class type without changing the original source of code and without the use of inheritance.

As -Is

The product quantity gets multiplied by price.

  1.     
  2.  public class OriginalClass  
  3.     {  
  4.         public  int TotalPrice(int productCount,int Cost)  
  5.         {  
  6.             return productCount* Cost ;  
  7.         }  
  8.     }  
  9.    
  10. class Program  
  11. {  
  12. static void Main(string[] args)  
  13.      {  
  14.          OriginalClass rate = new OriginalClass();  
  15.          int price = rate.TotalPrice(4, 1000);  
  16.      }   
To-Be

We want to provide flat 100 rupees discount to the final price.
 
Simple ways to do it,
  • Add a new method in Program class which will be having the logic of providing a discount on the final price.
  • Add a new class which will be inherited from OriginalClass class and having a new method which will go to calculate the final price based on the discount.
Issue with above approach

A consumer is only aware of the OriginalClass class and thus he will only be interested to create an object for the same parent class. For above approaches, child class object/reference needed to be created/used.

Solution

Use extension method which would help you to add a method to existing types without modifying the original source code and without the use of inheritance. 
  1. public class OriginalClass  
  2. {  
  3.    public int TotalPrice(int productCount,int Cost)  
  4.       {  
  5.          return productCount* Cost ;  
  6.       }  
  7. }  
  8.    
  9. public static class DiscountedClass  
  10. {  
  11.    public static int FinalPriceAfterDiscount(this OriginalClass obj, int productCount, int finalPrice)  
  12.       {  
  13.          // flat 100 rupees discount  
  14.          return productCount * finalPrice - 100;  
  15.       }  
  16. }  
  17.    
  18. class Program  
  19. {  
  20. static void Main(string[] args)  
  21.    {  
  22.       OriginalClass rate = new OriginalClass();  
  23.       int price = rate.TotalPrice(4, 1000);  
  24.       int discountedPrice = rate.FinalPriceAfterDiscount(4, 1000);  
  25.       Console.WriteLine("Price Without Discount :" + price);  
  26.       Console.WriteLine("Price With discount :" + discountedPrice);  
  27.    }  
  28. }  
Below is the output screen,

output

Note

  1. Use ‘this’ keyword in extension method parameter so that it refer to OriginalClass class when you invoke it in Program class. ’this’ will make sure that FinalPriceAfterDiscount method belongs to OriginalClass class as an extension method.
  2. An extension method must be defined in a non-generic static class.