Even though there are always many features added to each new C# version, most of them are more of “syntactic sugar” than a real feature programmers can benefit from. However, extension methods are one of those that can make a real difference in the way we code.
During all those years and various .Net versions introduced, this neat feature is undoubtedly one of my favorites. It is surely not suited for every single scenario or smaller project, but once you work on some enterprise applications, you can fully benefit from it. Not every programming language supports it, but thankfully, since the version 3.0, C# developers can take full advantage of it.
Extension Methods
An Extension Method is a programming feature that allows the developers to extend the existing type without having to derive it, recompile it or modify it by any means thus maintaining a better loose coupling. Existing types can be extended by adding methods only since Extension methods cannot add member variables. Even though this feature is helpful and OOP friendly, it is not a part of object-oriented programming. As Eric Lippert, a principal developer on the C# compiler team says:
"Extension methods certainly are not object-oriented. They put the code that manipulates the data far away from the code that declares the data, they cannot break encapsulation and talk to the private state of the objects they appear to be methods on, they do not play well with inheritance, and so on. They're procedural programming in a convenient object-oriented dress."
You can basically extend any existing type or interface you want. Even the base Object class can be easily extended making the newly added method available to all other types. All the standard LINQ query operators are the most common extension methods that add functionality to existing IEnumerable and IEnumerable<T> types.
Requirements
Even though every extension method must be declared as static, it acts as a classic object method you can call on every single instance, so there is no apparent difference between calling an extension method and the methods that are actually defined in an original type.
- must be defined as a static method
- must be defined in a static class
- this keyword must be used with the first parameter
Syntax
Besides encapsulating in a standard static method, we need to add the this keyword before the first parameter, so the framework can recognize what type are we extending. Extension methods are fully supported by IntelliSense, so once declared, you can use them as any other instance method.
-
- public static string StringExtension(this String str) { }
-
-
- public static int IntExtenstion(this int param) { }
-
-
- public static void InterfaceExtension(this IMyInterface myInterface, int i) { }
Note: if you declare the extension methods in a different namespace, you need to import it with the using keyword to be recognized by the compiler and IntelliSense.
Example
When using this neat feature, the sky is the limit, so there really are no borders when using the extension methods. In order to demonstrate how easy it is to add new functionality to an existing type, we will extend the “String” type and add a new method called “UpperFirst”. Its implementation is really simple since all it does is turning the first character of the string to upper case and the rest of it to lower case.
First, we start by declaring the extension method. As said before, it must be encapsulated in a static class as well as to be static itself. Pay close attention to the this keyword before the first parameter since this is one of the requirements. All it does is tell the framework what type we are extending (String in this case).
- static class Extensions
- {
- public static string UpperFirst(this String str)
- {
- if (String.IsNullOrEmpty(str))
- return String.Empty;
-
- return str.Substring(0, 1).ToUpper() + str.Substring(1, str.Length-1).ToLower();
- }
- }
Done and done. If you expected more, I need to say sorry, but that really is all you need. After the extension method has been declared, we can use it as any other object's methods in the rest of the application.
Figure 1: IntelliSense support
- string temp = "this is STRING";
-
- Console.WriteLine(temp.UpperFirst());
- Console.WriteLine("JUST another String".UpperFirst());
Figure 2: console output
Conclusion
The purpose of this article is to introduce extension methods as a powerful and easy to use programming feature. Even though not new, many developers are still not aware of it. As a result, much more complicated approaches are being used when extending existing types.