Using Extension Methods in .NET
Extension methods are a handy way of adding your own custom methods to a class when you normally wouldn't be able to. .NET treats extension methods exactly like instance methods. In fact, in your day-to-day .NET programming you may be calling extension methods and not even know it.
Let's say we have access to an API with a simple Person class. Also, for the purposes of this post, let's say we don't have access to extend or modify this class.
In order to get the full name of a Person we'd have to do something like this:
This is perfectly fine, but what if you have to do this in several places? You'd either have to copy/paste this code wherever you needed it (bad idea, what if your boss came in later and said that she really wanted to use middle name also? Then, you'd have to go manually change every line of code that gets the full name) or you could create a stand alone method to return the full name (a better option, but the new method would be separate from the class). Wouldn't it have been nice if the original authors of the class included a method to return a Person's full name? This is where extension methods come in handy. We can add a FullName() method and have it treated as if it was part of the class the whole time.
This is the syntax for creating an extension method. There are a few things to note here:
- Extension methods must reside in a public static class.
- Extension methods must be static
- Extension methods must use the this keyword in the parameter list of the function. This is how .NET knows what object to attach your extension method to (in this case, the Person class.)
Now that we have our extension method, we can call FullName() just like any other method belonging to the Person class.
Did you notice how the FullName() was declared statically, but is eventually treated as if it is an instance method? In fact, .NET treats all C# and VB extension methods in the exact same way as instance methods.
But, what about encapsulation? What if I don't want parts of my class to be exposed publicly under any circumstances? Don't worry, extension methods don't have access to any private or protected methods in a class.
This is a bit of a contrived example, in the real world, you would likely just modify or extend Person to add the FullName() method. You can just as easily add an extension method to a class you don't have access to:
Extension methods are a great way to add a level of simplicity and tidiness to your application. However, extension methods should be used in moderation. They are not always the right answer in every situation and should only be used when they make sense. Typically, if you can modify or extend the existing client code, you should.