Extension methods Using C#

Hi Friends,

In today’s section we’ll start discussion on extension methods. This is one of the powerful feature of c#, which helps you to extend the codebase by adding methods in the existing c# built in method. so, what these extension methods will do, basically it is treated as a shorthand or reusable component in my view which you find useful to be used in various places. hence, in that case, what i would be doing i’ll be creating one static method basically extending any .net type and adding my desired method in it. we can also extension methods to Classes,structs and interfaces. However, we can also extend generics like List<T> or IEnumerable<T>. so, basically it’s a enabling technology which is adding a third party codebase. so, Extension methods are basically easy to use and simple to write.

so, let get started. so, for this am going to add a new class library as shown below. Now, am going to arrange my extensions in one folder called my extensions. so, there are couple of rules associated with extension methods, these are there has to be static class and the method also has to be inside the static class and the last one is that type which we are extending should go into the signature with “this” keyword.


so, before we write the complete extension method, lets create test method for the same, so that we can see that how to consume these extension methods.


so, in the above case, i have written a extension method just to reverse the name, and if you have seen the same, this is very powerful technique to create the custom logic. so, let’s suppose we have some requirements which is custom to the project and is getting reused at various places, so for implementing the same, we could easily use Extension Methods. so, with this i would like to wrap this session, in the next session, we’ll delve more in extension methods. Till then stay tuned and happy coding.

Happy Coding

1,451 total views, 1 views today

This entry was posted in C# and tagged . Bookmark the permalink.