Extension Methods in C#

Extension Methods in C# with Examples

In this article, I am going to discuss the Extension Methods in C# with examples. Please read our previous article where we discussed Sealed Class and Sealed Methods in C#. At the end of this article, you will understand what exactly C# Extension Methods are and when and how to use these extension methods in C#?

What is Extension Method in C#?

It is a new feature that has been added in C# 3.0 which allows us to add new methods into a class without editing the source code of the class i.e. if a class consists of set of members in it and in the future if you want to add new methods into the class, you can add those methods without making any changes to the source code of the class.

Extension methods can be used as an approach of extending the functionality of a class in the future if the source code of the class is not available or we don’t have any permission in making changes to the class.

Before extension methods, inheritance is an approach that used for the extending the functionality of a class i.e. if we want to add any new members into an existing class without making a modification to the class, we will define a child class to that existing class and then we add new members in the child class.

In case of an extension method, we will extend the functionality of a class by defining the methods, we want to add into the class in a new class and then bind them to an existing class.

Both these approaches can be used for extending the functionalities of an existing class whereas, in inheritance, we call the method defined in the old and new classes by using object of the new class whereas, in case of extension methods, we call the old and new methods by using object of the old class.

Understanding Extension Methods in C# with an example:

Let us understand C# Extension Methods with an example. Create a console application and then add a class file with the name OldClass.cs and then copy and paste the following code in it.

public class OldClass
{
    public int x = 100;
    public void Test1()
    {
        Console.WriteLine("Method one: " + this.x);
    }
    public void Test2()
    {
        Console.WriteLine("Method two: " + this.x);
    }
}

Now our requirement is to add three new methods to the class OldClass. But we don’t want to change the source code of OldClass. Then we can achieve this with the help of extension methods. Let’s create a new class with the name NewClass.cs and then copy and paste the following code in it.

public static class NewClass
{
    public static void Text3(this OldClass O)
    {
        Console.WriteLine("Method Three");
    }
    public static void Text4(this OldClass O, int x)
    {
        Console.WriteLine("Method Four: " + x);
    }
    public static void Text5(this OldClass O)
    {
        Console.WriteLine("Method Five:" + O.x);
    }
}

Let us first test the application, then we will understand the extension methods. Now to test whether the methods are accessed using the old class objects or not, add a class Program.CS and write the following code

public class Program
{
    static void Main(string[] args)
    {
        OldClass obj = new OldClass();
        obj.Test1();
        obj.Test2();

        //Calling exrension methods
        obj.Text3();
        obj.Text4(10);
        obj.Text5();

        Console.ReadLine();
    }
}

Now, run the application and see everything is working as expected and it will display the following output.

Extension Methods in C#

Points to Remember while working with C# Extension methods:
  1. Extension methods must be defined only under the static class.
  2. As an extension method is defined under a static class, compulsory that method should be defined as static whereas once the method is bound with another class, the method changes into non-static.
  3. The first parameter of an extension method is known as the binding parameter which should be the name of the class to which the method has to be bound and the binding parameter should be prefixed with this keyword.
  4. An extension method can have only one binding parameter and that should be defined in the first place of the parameter list.
  5. If required, an extension method can be defined with normal parameter also starting from the second place of the parameter list.
Extension Method Real-time Example:

Let us see one real-time scenario where you can use the extension method. As we know string is a built-in class provided by .NET Framework. That means the source code of this class is not available to us and hence we can change the source code of string class. Now our requirement is to add a method to the string class i.e. GetWordCount() and that method will return the number of words present in a string and we should call this method as shown in the below image.

C# Extension Methods Real-time Example

You can achieve the above using Extension Methods. First create a class with the name StringExtension and then copy and paste the following code in it. As you can see, here we created the class as static and hence the GetWordCount as static and provide the first parameter as the string class name so that we can call this method on the string class object.

namespace ExtensionMethodsDemo
{
    public static class StringExtension
    {
        public static int GetWordCount(this string inputstring)
        {
            if (!string.IsNullOrEmpty(inputstring))
            {
                string[] strArray = inputstring.Split(' ');
                return strArray.Count();
            }
            else
            {
                return 0;
            }
            
        } 
    }
}

Once you have created the extension method, now you can use that method on the string class object. So, modify the Main method of the Program class as shown below.

namespace ExtensionMethodsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string myWord = "Welcome to Dotnet Tutorials Extension Methods Article";
            int wordCount = myWord.GetWordCount();

            Console.WriteLine("string : " + myWord);
            Console.WriteLine("Count : " + wordCount);

            Console.Read();
        }
    }
}

That’s it. Now run the application and you should get the output as expected as shown in the below image. 

Real-time Example of Extension Methods in C#

In the next article, I am going to discuss C# 7 new Features with examples. Here, in this article, I try to explain Extension Methods in C# with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Extension Methods in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *