Extension method in C#

In this article we are going to explain you about Extension method in C#. It was introduced in C# 3.0 and used to extend the functionality of a class or type. How we can create it, what are its benefits, let’s discuss all with the help of example below.

Extension methods are always created as static methods and also created in Static class. These are basically used to extend the functionality of class or type without making any change in your actual class.

Extension method for type ‘String

Below we have Class named “CodeConfig” and it is static. Next, we have created two extension methods as given below.:

  • “RemoveSpecialChars(this string str)” 
  • “ConvertMultipleWhiteSpacesToSingle(this string str)” 

Both the methods are static, and they accept one input parameter of type string, and which is decorated with “this” keyword which is the basic requirement of Extension method. Now once you will add dot after string type then above extension methods can be seen as

Extension method in C#

You can see both extension methods as below.

Extension method in C#

Extension method example in C# for type String

namespace ExtensionMethod
{
    public static class CodeConfig
    {
        public static string RemoveSpecialChars(this string str)
        {
            if (str != "")
            {
                // Your logic can be here.  
                return str.Replace("#", "").Replace("@", "").Replace("$", "").Replace("^", "").Replace("&", "").Replace("*", "").ToString();
            }
            else
            {
                return "";
            }
        }
        public static string ConvertMultipleWhitespacesToSingle(this string value)
        {
            return Regex.Replace(value, @"\s+", " ");
        }
    }


public class Program
    {
        public static void Main(string[] args)
        {
            string st = "@Rakesh#  Kumar#.I am from     India.";
            st=st.RemoveSpecialChars();                   
            st = st.ConvertMultipleWhitespacesToSingle();
            Console.Write(st+"\n");

            Console.Read();
        }

    }
}

Extension method for a Custom class

As we create Extension method above for type String now, we’ll create extension method for a custom class. Suppose we have one class which has two methods, and we need to add new method, but we do not have access to actual class then using Extension method we can add third method which will further be accessed using actual class object.

Let’s discuss it with the help of example.

Below we have actual class named “Bank” which has two methods named “SimpleInterest” and “CompoundInterest”and if we want to add third method “CheckLoanEligibility” then we can add this using extension methods as shown in below image.

Extension method in C#

Now, we have created above extension method. In extension method as input parameter, we’ll pass the name of class name whose extension method we want to create, and it is always decorated with “this” keyword.  Additionally, this class must be the first parameter only. If you’ll place this at any other position apart form first, then you will get compile time error.

Let check if we can access our extension method by using Bank class object. See in below code we can access existing two methods and new extension methods too using Bank class object.

Extension method in C#

Example of Extension methods in C#

namespace ExtensionMethod
{
    public class Bank
    {
        public void SimpleInterest()
        {
            Console.Write("1.Simple Interest Function\n");
         }
        public void CompoundInterest()
        {
            Console.Write("2.Compound Interest Function\n");
        }
    }
    public static class ClientClass
    {
        public static void CheckLoanEligibility( this Bank b)
        {
            Console.Write("3.Check Loan Eligibility Function\n");
        }

    }
    
    public class Program
    {
        public static void Main(string[] args)
        {

            Bank obj = new Bank();
            obj.SimpleInterest();          // actual method of Bank class
            obj.CompoundInterest();        // actual method of Bank class
            obj.CheckLoanEligibility();    // We can access extension methods too.  
            Console.Read();
        }

    }
}

Key points of Extension methods

  • Extension methods are always defined as a static method and in static class and can be used in non-static class too.
  • Extension method is also feasible on sealed classes.
  • If an extension method is created with the same name and the signature of its actual class’s method, then the compiler will print the actual class method only. Hence method overriding is not possible in extension methods.
  • As name indicated extension methods used to extent methods or types and it cannot be used for properties and events.
  • In extension methods multiple input parameter should be avoided and class whose extension method we want to create must be as first parameter only (with this keyword).
  • One of the main advantages of extension methods is that we can add new methods in the existing class without even modifying the existing class code.

What is the difference between extension method and static method in C#?

Extension method is used to extend the functionality of existing class and make the code more readable and reusable. All methods (existing and extension method too) can be access by using the object of actual class. On the other hand, static make life easier to call method directly by the name of class (without object) but it does not offer the reusability similar to extension method. So, you can pick the one as per your program needs.

Is LINQ an extension method?

Yes, all LINQ methods are actually extension methods.   

Where to use extension method in C#?

It can be used when you do not have access to actual class or actual class is sealed and you are not able to inherit and extend its functionality then extension method makes our life easier and give us option to extend actual class using extension methods. After creating extension method, we can access this new extension method using the object of our actual class. It also increases code reusability, and all methods (actual class’s method and extension methods) can be access by same object.

Should we use extension methods?

Yes, extension method feature was added in C# 3.0, and it is a valuable addition to the C# language. It helps us in writing nicer, reusable and more readable code. One must use this OOP feature.

Are extension methods thread safe C#?  

No, generally extension methods are not thread safe.

We hope above explanation of extension methods has cleared your doubt of the same. For more information you can check out Microsoft learn.

For more information you can visit our C# Section for more such articles.

Leave a Reply

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