Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extension Methods in C# Explained

0.00/5 (No votes)
14 Sep 2015 1  
Extension methods is a feature which was introduced in C# 3.0. Extension methods in C#

Introduction

This article is 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 follows:

Extension method in C#

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 the 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 exist with a special symbol, i.e., a down arrow next to it and the tooltip really shows that it is an extension method.

Extension methods in intellisense in C#

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 the Compiler Know About the Extension Methods?

When the compiler sees 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 a single parameter of type string. If an existing method 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 take 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

  • We need to import the namespace in which the static class is defined which contains the extension methods. Suppose I have defined my CapitalizeFirstCharacter method in a class StringExtension which is again defined under namespace. In that case, we need to include the namespace using the keyword using wherever we want to use the CapitalizeFirstCharacter method.
  • C# only supports extension methods, it does not support extension properties, extension events, extension operators.
  • Extension methods must be declared in non-generic and static classes.
  • C# compiler looks only for the extension methods defined in static classes that are themselves defined at the file scope. In other words, if we define a static class in some class and then define our extension methods, in that case, we will get a compile time error as shown below.

    Extension method declaration in C#

  • It is possible that multiple static classes can implement the same extension method. In that case, we will get a compile time error as shown below.

    Ambiguous extension methods in C#

  • The only way to overcome this error is to change the source code.
  • If we are extending a type with some extension methods in C#, in that case all the derived types are also eligible for this method’s utilization. Suppose if we are extending System.Object, then all the types will have that particular extension method. That is why we should use this feature very sparingly and with caution.

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.

The post Extension Methods in C# Explained appeared first on Dot Net For All.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here