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:

public static class wrapper
    {
        public static string ChangeCase(this string mystring)
        {
            if (mystring.Length > 0)
            {
                char[] array = mystring.ToCharArray();
                array[0] = char.IsUpper(array[0]) ? char.ToLower(array[0]) : char.ToUpper(array[0]);
                return new string(array);
            }
            return mystring;
        }
    }

Program Class:

  class Program
    {
        static void Main(string[] args)
        {
            string mystring = "fwait";
            Console.WriteLine(mystring.ChangeCase());
        }
   
    }