Extension methods in C#

 Oct 27, 2014

In today’s blog post, I will address the issue of extending an object definition when you don’t have access to the source code or you can’t inherit from the original object. Imagine you have received a DLL from a third party containing an object model you want to incorporate into the application you are currently developing. Due to the IP measures by the third party development company, you have a copy of the DLL but no source code could be made available to you. Let’s say the object model includes an Order class with heaps of useful methods that meet most of your requirements. So, you can create an instance of the Order class and then call methods like PlaceOrder, ChangeOrderDetails, GetCustomer, GetProductsList among many others. Now let’s say you need a method that evaluates the risk of a customer not being able to pay the bill for a particular order. The instance of the Order you have allows you to get the customer and the list of products in the order and you could write code that uses that information and pulls additional info about the credit history of the customer and you could end up with some kind of risk metric to use as the return for the method. But you want all that code to be an integral part of the Order class, so that you simply call it from the instance variable representing the order.
Order order1 = new Order(…); double risk = order1.EvaluateRisk();
If you could modify the source code, you would simply add the new method definition directly to the Order class and be ready to start using it as above. But you have no access to the source code! The next idea would be to create a new class, say OrderExt, that inherits from Order and then add a method EvaluateRisk to it.
public class OrderExt : Order { public double EvaluateRisk() { … } }
If the Order class was declared as sealed in the DLL you received, this approach wouldn't work because you wouldn't be allowed to create a derived class from it.
public sealed class Order { /*you can’t inherit from a sealed class*/ … }
In such a scenario, extension methods come to your rescue. Using Extension Methods, you can add methods to existing classes without creating a new derived class, recompiling, or otherwise modifying the original class. An extension method is a special kind of static method, but you call it as if it were an instance method on the extended type. After you define an extension method EvaluateRisk for the original class Order you just call it as if it were an ordinary public method of the Order class. To create the extension method, you need to create a static class and then define a public static method with an additional parameter with the type of the extended class that precedes all the other input parameters for the extended method. The name of this static class can be anything as it is not to be used explicitly anywhere.
public static class MyExtensions { public static double EvaluateRisk(this Order order1) { … } }
Note, that the first and in this case, only parameter of the static method EvaluateRisk has the type Order which is the class we want to extend and it is declared with the keyword this. If the extension method we want to add to the extended class was expecting some input parameters they would follow this special first one. Once we have defined the extension method as above, we can simply call it with any instance variable for an Order, for example order1.EvaluateRisk(). To learn more about C#, we recommend the course 20483: Programming in C#.

How do your Excel skills stack up?   

Test Now  

About the Author:

Newton Godoy  

With over 17 years of in-class training experience and over 16 years of industry experience, Newton offers students a wealth of real-world technical knowledge and expertise in the areas of .NET application development, SQL Server and SharePoint Server. After spending several years lecturing as a professor, Newton found his true calling and began his career as a MCT. He worked as a technical trainer for some of Brazil's and Australia’s largest corporate training organisations before finally finding a home with New Horizons where he is now one of our top trainers. Newton brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. His combination of technical knowledge and instructor experience make him one of the most respected instructors within the IT training industry.

Read full bio
top
Back to top