Extension Methods in C#

 In some of my most recent articles, we saw what inheritance, polymorphism, and interfaces are and how they are implemented in C#. In this article, we will discuss another important C# concept. We take a look at what extension methods are, how they are used, and how can we implement them in C#.

What are Extension Methods?

Extension methods are methods that can be added to a type without modifying the actual definition of the type.  Extension methods promote the concept of reusability. For example, you have created a class which performs all of the desired functionalities. At some point in time, you need additional functionality. So, at that time, rather writing the whole class from scratch, you can use extension methods to add functionality to the existing class.

Suppose you have created a class named “Circle” and in the definition of this class you have added one method “DrawCircle.” Now, you want to add another method “DeleteCircle” to the class, but for whatever reason, you do not want to alter class definition, you can still add this “DeleteCircle” method as an extension method to the “Circle” class.

How to Create an Extension Method

An extension method is a static method inside a static class. The difference between a normal method and an extension method is that you have to add “this” keyword before the first parameter in the extension method. Also, the type of the first parameter is the type that is going to be extended by the extension method. Take a look at the following example.

public static class StringExtension
{
    public static string GetLastHalf(this string sentence)
    {
        if (!string.IsNullOrEmpty(sentence))
        {
            int middle = sentence.Length / 2;
            string lastHalf = sentence.Substring(middle);
            return lastHalf;
        }
        else
            return null;
    }
}

Take a close look at the above code snippet. Here we have defined a static class named “StringExtension”. You can have your own class name. It doesn’t matter. Inside this class, we have a static method named “GetLastHalf”. Notice this method has the “this” keyword before the first parameter which makes this method an extension method. The first parameter is of type string which means that this method is going to be added as an extension method to string class.

Basically, this method operates on a string value and returns the last half of the string. If there is an even number of characters in the string, it returns last n/2, characters of the string where n is the total number of characters in the string. However, if there is an odd number of characters in the string, the GetLastHalf() method returns the last (n/2 +1),  characters, where n is the total number of characters in the string.

Now there are two ways to call extension methods. Take a look at the following code snippet.

Console.WriteLine("Canada".GetLastHalf());
Console.WriteLine(StringExtension.GetLastHalf("England"));

You can call an extension method directly via string literal or you can use the static class of the extension method and then call the extension method on it while passing parameters to it. The first method is the preferred one.

Extension Method Chaining

Like normal methods, extensions methods can be chained together to perform multiple functionalities via a single line of code. Method chaining can be defined as the process of executing multiple methods in series by appending them together via the dot “.” operator. Take a look at the following example.

public static class StringExtension
{
    public static string GetLastHalf(this string sentence)
    {
        if (!string.IsNullOrEmpty(sentence))
        {
            int middle = sentence.Length / 2;
            string lastHalf = sentence.Substring(middle);
            return lastHalf;
        }
        else
            return null;
    }

    public static string GetFirstHalf(this string sentence)
    {
        if (!string.IsNullOrEmpty(sentence))
        {
            int middle = sentence.Length / 2;
            string firstHalf = sentence.Substring(0, middle);
            return firstHalf;
        }
        else
            return null;
    }
}

In the above example, we have added another method named “GetFirstHalf”. This method will retrieve the first half of the string on which this method is called.

Now, to see how these methods are actually executed. Take a look at the following code snippet.

Console.WriteLine("Argentina".GetLastHalf());
Console.WriteLine(StringExtension.GetFirstHalf("Argentina"));
Console.WriteLine("Argentina".GetLastHalf().GetFirstHalf());

Here in the first line, we call the “GetLastHalf()” extension method on the string “Argentina” which has 9 characters. Since 9/2 is 4.5, we ignore the fraction which gives us 4. And because the total number of characters is odd the last five characters will be 4+1. So on the console the string “ntina” will be printed.

For the second call, the string “Arge” will be printed.

Now on the third line of code, the GetLastHalf() and GetFirstHalf() methods are chained together on the string “Argentina”. When this line of code executes the GetLastHalf() method returns “ntina”. On this returned string, the “GetFirstHalf()” method is called which will return “nt”  The output of the code in the above example will look like this:

ntina
Arge
nt

Extension Method Precedence

Now consider a scenario where two classes have extension a method with the same name. Which method will be executed if called via a class? In other words which method will take precedence when called if both the methods have the same name? Take a look at the following example to better visualize this problem.

public static class StringExtension
{
    public static string GetLastHalf(this string sentence)
    {
        if (!string.IsNullOrEmpty(sentence))
        {
            int middle = sentence.Length / 2;
            string lastHalf = sentence.Substring(middle);
            return lastHalf;
        }
        else
            return null;
    }
}

public static class StringExtension2
{
    public static string GetLastHalf(this object sentence)
    {
        if (!string.IsNullOrEmpty(sentence.ToString()))
        {
            int middle = sentence.ToString().Length / 2;
            string lastHalf = sentence.ToString().Substring(middle);
            return lastHalf;
        }
        else
            return null;
    }
}

In the above example, we have two classes StringExtension and StringExtension2. Both the classes have an extension method “GetLastHalf()”. If we call this method on a string literal such as “England”, which of the methods will be executed? The answer is, the method whose parameters are more specific to the method call will be executed if both the methods have the same name.

If you look at the above code the ‘’GetLastHalf()” method in the StringExtension class has a first parameter of type string, whereas in the “GetLastHalf()” method in the StringExtension2 class has a first parameter of type Object. Though a string is also an object but in terms of precedence, the method with the “string” type parameter will take precedence if it has a name matching another method.

In this article, we discussed extension methods in C#. We went over what they are and how to declare them. If you found this article helpful be sure to check out my C# Roadmap