There are so many scenarios in which we developers need to extend the capabilities of a class. Most of the time we cannot go and change the class, so we may have to go for some OOPS concepts like inheritance in order to get this done.
What if the class belongs to a Microsoft .NET assembly?
What if the class is ‘sealed’?
Here I am going to explain a C # 3.0 feature which I explored recently.(And became a fan of it!)
So what actually is this Extension Methods?
Extension method is a syntactic sugar, syntax within c# to make things easier. It helps to “add” methods to an existing type without modifying the original type. These are “static” methods which require an instance of an object. So this feature will not support “static” classes.
Let us consider a simple example to illustrate this feature.We can try adding a method,PrintMe() to the ‘String’ class in the System namespace of mscorlib.dll .NET framework assembly.
The first thing that we need to do is, to create a ‘static’ extension class. Now we can write a ‘static’ method PrintMe() inside this class. This method should have the first parameter as instance of string class preceded by ‘this’ keyword.i.e. the first parameter should point to the type in which the method needs to be operated.
The extension class goes like this,
Now let us try invoking this method from an instance of String class,
There you go! The visual studio intelliSense is showing PrintMe() method as well! By mentioning it as extension.
Thus we are done with a “Hello World” example of Extension Methods. There is a lot more to explore!