Dot Net For All

Extension Methods in C# Explained

Extension Methods in C# Explained

This is the article in continuation of my article series about the methods in C#. In my previous articles I have discussed about the constructors and operator overloading methods. Extension methods is a feature which was introduced in C# 3.0. Extension methods in C# are used to extend the functionality of a class which is not provided by the class itself, without altering the definition of the original type.

Syntax

An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Please find the example of the extension methods in C#, in the code snippet provided below whose utilization I will be discussing down the line.

public static class StringExtension
    {
        public static string CapitalizeFirstCharacter(this string strPara)
        {
            StringBuilder capitalizedString = new StringBuilder();

            string[] allWords = strPara.Split(null);
            foreach (string item in allWords)
            {
                capitalizedString.Append(Regex.Replace(item, @"^\w", m => m.Value.ToUpper()) + " ");
            }

            return capitalizedString.ToString();
        }  
    }

Extension Method Utilization:

As I have already discussed, Extension methods are used to extend the functionality of the existing class.  I have created an extension method for the String class to get the first letter in upper case of each word in the string.

            string myName = "my name is vikram";
            string firstCharacterUpper = myName.CapitalizeFirstCharacter();
            Console.WriteLine(firstCharacterUpper);
            Console.ReadKey();

And the output of the above code will be as following.

Suppose if the extension methods would not have been in existence, in that case we had to create a static class and defined a static method in the same class. The method CapitalizeFirstCharacter, would have been defined in our case as shown below

   public static class StringExtension
    {
        public static string CapitalizeFirstCharacter(string strPara)
        {
            StringBuilder capitalizedString = new StringBuilder();

            string[] allWords = strPara.Split(null);
            foreach (string item in allWords)
            {
                capitalizedString.Append(Regex.Replace(item, @"^\w", m => m.Value.ToUpper()) + " ");
            }

            return capitalizedString.ToString();
        }  
    }

And we could have used this method as shown below

           string firstCharacterUpper = StringExtension.CapitalizeFirstCharacter(myName);
           Console.WriteLine(firstCharacterUpper);
           Console.ReadKey();

Now there is no problem with this approach but it is not ideal from programmer’s point of view. The first problem with this traditional approach is that, the developer would not know if there is a method which exists in some static class which helps us to achieve the desired functionality. The second problem with this approach is that the static class and static method overpowers and detracts a programmer’s mind from the operation that is performed.

But if we look at the first approach of the usage of extension methods, we can see that Visual Studio’s intellisense provides the ease to see the function while working on the string class as shown in the figure below. As we can see the extension methods exists with a special symbol i.e. a down arrow next to it and the tooltip really shows that it is an extension method.

And now while using the extension methods we are pretty sure about the operation that we want to execute on the string class.

How does compiler knows about the extension Methods ?

When the compiler sees the the code in the following line :

string firstCharacterUpper = myName.CapitalizeFirstCharacter();

The compiler first checks if the String class or any of the base classes offers an instance method called CapitalizeFirstCharacter() that takes single parameter of type string. If an existing methods exists, then the compiler emits the code to call it. If no matching instance is found, then the compiler will look at any static classes that define static method called CapitalizeFirstCharacter() that takes their first parameter as a type matching the type of the expression being used to invoke the method i.e. a string in our case.

Rules to Use Extension Methods:

 

Conclusion

In this article I have discussed all the important points related to extension methods and I believe that I have made the concepts about them quite clear.

Please let me know your feedback about the article.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview