Extension Methods in C#

Extension Methods in C#
Rating: 5 - 2 Votes

Extension Methods in C#

Extension methods were introduced in dotnet framework 3.5.  C#Extension methods are basically an instance methods which are added to an existing type without creating a new derived type, recompiling, or originally modifying the code.  C# dotnet framework has provided us a lot of extension methods like where, aggregate, average etc.

Behind the scenes, all extension methods are static methods which belongs to a certain class.  This class is also known as wrapper class and it’s a static class.  The first parameter of extension method in wrapper class always starts with this keyword because this represents which type you are trying to extend.  If you are trying to extend string class, then it should be like this string ParameterName.  Then, this extension method can be called on instance level of an extended type.

The question arises here is that where these methods are useful or where to use them.  As we know, code maintenance is very tedious task and day by day a developer does try to improve his code due to maintenance and performance reasons.  If you do not want to use extension methods, then you can add more methods to existing class or create a new class and add your desired methods and finish the job.  But what if you don’t have access to existing class or even if you add one more class, then now you have 2 classes to maintain.

Extension methods eliminate the possibilities of above scenarios and you can still add more methods to the existing type without modifying original code in any manner.  Even a sealed class can have more methods with the help of extension methods.

The above logic can be better understood with an example given below where we have 2 classes, program and wrapper class.  Wrapper class has a method called ChangeCase(), which will change the case of the first letter in a string.

Wrapper Class:

Program Class: