I’ve been talking about Object-Oriented Principles for a while, and this post will not be different. Here and here, I’ve introduced OOP and described an elegant solution to comply with Open-Closed Principle using Visitor Pattern, respectively. Today I’ll be talking about a C# 3.0 feature called extension methods. Maybe you’re now asking what extension methods and OOP have in common. That is what this post is about.
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
Therefore, extension methods are an optional technique to extend classes functionalities without modifying it. This makes me remember the Open-Closed Principle which states that software entities should be open for extension, but closed for modification. By using extension methods, your software tends to be less difficult to change, to not impact in dependent modules and even more important, changes are achieved by adding new code, not by changing old code that already exists.
Extension methods are defined as static methods in static classes, but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. The following example shows extension methods for C# string class.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. They are used as if they were instance methods and are visualized in VS intellisense, as show below:
Here is the test class for StringExtension.cs class showing how to invoke extension methods in C#.
As you could see, this feature enables you to extend the string class, which is a sealed class, same as final class in Java, and implossible to inherit it. This helps you to extend and maintain code in a really elegant way. So, remeber using extension methods when find similar problems in you code.