Skip to main content

C# Advanced Topics - Extension Methods

Extension Methods

What are extension methods ? 

Extension methods provide us the ability to add methods to an existing class without changing its source code or creating a new class that inherits from it . 

Extension methods are the static methods but they are called as if they were instance methods on the extended type . 

Before we dig deep , lets find our reason on why does it came into existence ?  Why and when should or we are recommend to use an extension method in your application . 

Let me show you an example here : 

 Lets consider a scenario where we need to shorten the number of characters displayed based on the passed input . So as String being a sealed class we are neither allowed to inherit or extend it.This is where the extension methods are quite helpful . Define a static class that holds a static method which takes numberOfWords as one of its parameter and return a string . Their first parameter will be the type on which the method operates . The parameter is preceded by this keyword . In the below code the output now only returns four words . 




But from the above code we need to note that as the program class and extension static class are on the same scope but in real time the static class is written in a separate class where we need explicitly import the namespace into your source code with a using directive to use those extension methods such as 
using StringExtensions;

The extension method always have lower priority at compile time when compared to instance methods. When the compiler encounters a method invocation , it first looks for match on instance methods and if not found it searches for extend methods that are defined for the type .

So the extension methods at times can be troublesome . The problem  here is you extended the String class with Shorten method but what if the creator of the string class i.e the Microsoft in one of its releases plans to create an Shorten method exactly with the same signature but it may behave differently from your code . What happens is that the instance method gets priority over the extended (static) method so your method is never executed . 

For the same reason , Microsoft in its guidelines suggests to use extension method only when you really have to .  If you have the source code for the original class go ahead and change there otherwise create a new type that derives from that class and add your new method there and if that doesn't work the  go ahead and create the extension method . 

In the real world practically  most of the times you will be using extension methods instead of creating them . A very good example of that is IEnumerable 



From the image above we can see that Min , Max , OrderBy and so on are   methods defined in the IEnumerable type. Having a look at this methods suggestion we see all of these are extension methods .Here it is saying that these extension methods are defined in the namespace Linq .

Min method there returns the smallest number from that list . So we just understood that extension methods are quite helpful and most often we will be using them as opposed to using them . 

So finally if you do implement an extension method , do remember the following points 
  • Extension methods must be brought into scope at the namespace level .
  • An extension method will never be called when it do have the same signature as of the instance method .
 


Comments

Popular posts from this blog

C# Advanced Topics - Generics

Generics  Before we start learning What Generics is ?  , let me explain what problem generics came to solve . In .NET version 1 , we don't have generics .So ,lets say we need to create a list to store a list of numbers . The implementation of that class looks like below :  Currently , as I am not concentrating on how data structures works , just assumed a sample list class with  only Add method , which add the passed integer into its list. Rather than defining all the methods like Remove , find and properties and functionality and so on , just planned to have my class and projected on how generics came into existence . Let me define a simple class object here :  Now , if i plan to store a book to the list defined above it doesn't work as int is a value type and our book class will be a reference type . So , I am forced to create some class like below, which will give the ability to add a list of books :  So , th...

C# Advanced Topics - Lambda Expression

Lambda Expression  So what is a lambda expression and why are these lambda expression used for ?  As every article of me says you what and why , here as well we are going to get an answer for it .  A lambda expression is nothing but an anonymous method .   Oh really !! But what is anonymous method here ? It might be the next question which strikes you . Just follow through get an answer for it .  An Anonymous method is a method with no access modifier , no name and no return statement . But apart from this book definition we can look its snippet for a better understanding. Before that why do we use them ? Any guess ?  For convenience . We can write less code and achieve the same thing plus our code will be more readable readable . For our practical knowledge , lets take an example , lets say we would like to write a method which takes a number and returns cube of the number . Typically , this is how we do that   Now with lambda expression w...

C# Advanced Topics - Delegates

Delegates So what is a delegate ?  and Why does it come into existence ? A delegate is an object which knows how to call a method(or a group of methods). Simpler way to define is, delegate is a reference or a pointer to a function .  Now why do we need like that ? We can call methods directly , why do we need a delegate that is calling methods for us . Well this technique is helpful for us in designing extensible and flexible applications.  If we are asked to create a framework for image processing , So it looks some thing like this  So ,if I release this framework,the client or developer who is consuming the framework can use this as below and it might look as below  Now if one of the developer  wanted to apply another filter to resize the image , you need to create that filter and  re-compile and re-deploy both ImageFilter and ImageProcessor classes. Now imagine every time a developer in the world want a new filter you need to re-compile and and re-...