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.
-
- public class OriginalClass
- {
- public int TotalPrice(int productCount,int Cost)
- {
- return productCount* Cost ;
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- OriginalClass rate = new OriginalClass();
- int price = rate.TotalPrice(4, 1000);
- }
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.
- public class OriginalClass
- {
- public int TotalPrice(int productCount,int Cost)
- {
- return productCount* Cost ;
- }
- }
-
- public static class DiscountedClass
- {
- public static int FinalPriceAfterDiscount(this OriginalClass obj, int productCount, int finalPrice)
- {
-
- return productCount * finalPrice - 100;
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- OriginalClass rate = new OriginalClass();
- int price = rate.TotalPrice(4, 1000);
- int discountedPrice = rate.FinalPriceAfterDiscount(4, 1000);
- Console.WriteLine("Price Without Discount :" + price);
- Console.WriteLine("Price With discount :" + discountedPrice);
- }
- }
Below is the output screen,
Note
- 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.
- An extension method must be defined in a non-generic static class.