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.
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.
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.


Vinay AyinapurapuPosted Apr 15, 2021, 2:38 PM
Nicely explained.
Gajendra JangidPosted Feb 2, 2018, 7:28 AM
Vary nice article...............