Extension Methods in C#

Extension Methods are introduced in C# 3.0. These methods are used to extend the functionalities of existing classes and for that there is no need to modify, extend or recompile the existing class.

With the help of Extension Methods you can easily add new functionalities to the InBuild classes like String, Integer, etc. or it can be your own custom class.

You can achieve this :

  • Without modifying the existing class, means you are not required to add code in the existing class.
  • Without creating a derived type, means no need to extend the class
  • Without recompiling the class.

So now the Question is how you gonna do this.

For that you need to create a static class with public access specifier which contains your public static extension method(s), One thing to note here is the parameter(s) of the extension methods. Read the following example carefully for complete understanding



A Glimpse of Extension Method-

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; //StringSplitOptions is a inbuilt function of System namespace.
        }
    }   
}

Key Notes:

  • Here WordCount is the name of our new extension method.
  • Notice that it is made static and its visibility is public
  • Also note that the class containing the method is also made public and static
  • Parameter of the method is using this keyword
  • It is important to use this keyword as the type used with ‘this’ keyword tells that this extension method is going to work with that particular type(eg. string). And moreover that method will be called by a string instance using the dot operator
  • So from the above statement you can say that these are the static methods but are used as instance methods.
  • The class can either be in the same namespace where you required to use the extension methods or you can import the namespace like other using the ‘using’ keyword
  • You can create extension method with more parameters, but remember all the other parameters except the first one with ‘this’ keyword, you have to pass the value for them.

Complete Example of Extension Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntensionMethodDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "seekyourcarrer.in";
            name = name.UpperFirstLetter();  // extension method
            Console.WriteLine("Calling UpperFirstLetter() : " + name);

            string result = "seek your career dot in";
            int count = result.WordCount();   // extension method
            Console.WriteLine("Calling WordCount() : " + count);

            int num1 = 20;
            Console.WriteLine("Calling MultiplyBy() :  " + num1.MultiplyBy(30));   // extension method  
            Console.ReadKey();
        }
    }

    public static class ExtensionString
    {
        //Converts a string value with only first letter to Upper Case
        public static string UpperFirstLetter(this string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                char[] array = value.ToCharArray();
                array[0] = char.ToUpper(array[0]);
                return new string(array);
            }
            return value;
        }

        //Count the words in a string and return the count as interger value
        public static int WordCount(this string value)
        {
            value = value.Trim();
            if (!string.IsNullOrWhiteSpace(value))
            {
                int wordcount = 1;
                for (int i = 0; i < value.Length; i++)
                {
                    if(value[i] == ' ')
                    {
                        wordcount++;
                    }
                }
                return wordcount;
            }
            return 0;
        }
    }

    public static class ExtensionInteger
    {
        //Multiply an Integer with another integer value passed as argument and return their result as Integer type
        public static int MultiplyBy(this int num1, int num2)
        {
            return num1 * num2;
        }
    }
}

Explanation of above Example

In the above example we have created three extension methods, two for String and one for Integer. In string class there is no method to count the number of words in a string. So we created WordCount() extension method which is accessible with any string by using the dot operator. Notice that while creating we have mentioned one parameter of string type and at the time of calling that extension method we have not passed any string value , the reason behind this is that the first parameter of extension method is defined with ‘this’ keyword and so its value is taken from the operand on which it is called. Any additional parameters if it takes like in MultiplyBy extension method then we have to pass them at the time of calling like in line 22.
extension method

Do You Know : All the methods in Linq namespace are extension methods.

Tip :
These methods are very helpful when you want some additional functionality in the VS in-build classes because there you cannot modify the metadata of these classes, then these extension classes are a life saver and saves a lot of your time.