There are many times when we might want to add functionality to existing code. The existing code could be the classes written by fellow developers in our team or it could be third party code that we might want to use.
The obvious choice is to create a new class by inheriting the existing class and add functionality to this newly created class. This is a good option if your inheritance is logical and you have access to existing class. What I mean by ‘Logical Inheritance’ is that your inherited class should add significant functionality on top of existing class and is logical. For example, you can inherit DataAccess class to create MySQLDataAccess class but not some BusinessClass. The second condition is that you should have access to existing class. You cannot inherit from a Sealed class, for example
You can use .Net extensions if you don’t have access to existing class or if you want to tweak the existing class to add a bit of functionality.
Let’s consider you have below class SealedClass in which you want to add Subtract functionality. As this is a sealed class, we cannot inherit from it.
public sealed class SealedClass { public int operandA {get; set;} public int operandB {get; set; } public int Add() { return operandA + operandB; } }
You can use .Net Extension methods here. All you need to do is to pass your instance to the method with this keyword so that the method will act as a method of the passed class. You can add whatever functionality you would like to add by accessing the instance.
public static class ExtensionMethods { public static int Subtract(this SealedClass c) { return c.operandA - c.operandB; } public static void AddBothOperands(this SealedClass c,int value) { c.operandA = c.operandA + value; c.operandB = c.operandB + value; } }
Now you can access to these method as though you access the method of the class SealedClass.
class Program { static void Main(string[] args) { SealedClass scObj = new SealedClass(); scObj.operandA = 10; scObj.operandB = 5; Console.WriteLine("Sum:"+scObj.Add()); //Ouputs Sum:15 Console.WriteLine("Difference:"+scObj.Subtract());// Outputs Difference:5 scObj.AddBothOperands(5); // Method with parameter Console.WriteLine("Sum:"+scObj.Add());//Outputs Sum:25 } }
Thanks for reading. If you like this article, please subscribe below so that I can send articles straight to your inbox.
[mc4wp_form]
Leave a Reply