Extension Methods
One of the features of C# 3.0
Problem
Normally, in a situation where it is necessary to add more functionality to a class - for instance a new method - it would simply be a matter of modifying the class' source code and recompiling the binaries with these new changes to make this effect. However, in some cases, especially when it comes to classes that are build-in into the .NET-framework or reside in third-party assemblies, the programmer does not have access to the source code and is thus unable to change the behavior of the class directly. Heretofore, the programmer has been left with two other less intuitive options:
- The first option is to inherit the class and then add the functionality.
- The second option is to make a new, separate class and add a static method that takes an object of the class type and return a new object with the modification of choice.
Current Solution
The first option sounds simpler, but actually it is harder, because sometimes you can't do this, because inheritance has some limitations, like you can't inherit a sealed class, or a primitive data type such as int, float, ... etc. Ok, we still have the second option, which is writing a class anywhere, and add the function to it as static function. However, you can't do something like this
string x = "some string value"; string y = x.Reverse();
which you can't use the function as if it is part of the class itself, and you will end up with code similar to this
string x = "some string value"; string y = Util.Reverse(x);
that's because you wrote the Reverse function the Util function.
Extension Methods
in C# 3.0 you can configure the Util.Reverse() function to make the first code doable, so consider the following code of Util.
public static class Util { public static string Reverse(this string input) { char[] reversedChars = new char[input.Length]; for (int i = input.Length - 1, j = 0; i >= 0; --i, j++) { reversedChars[j] = input[i ]; } return new String(reversedChars); } }
as you can see it is a simple static class, with one static function called Reverse, all what we have to do
- Make sure that the class is static
- Add this keyword before the type of the argument you want to extend.
so now you can write this code,
string x = "some string value"; string y = x.Reverse()