Custom Extension Method In C#

Introduction

Here, we will learn how to create custom extension methods and use them.

Prerequisites

  • Visual Studio
  • Basic knowledge of C#

Article flow

  1. What is the Extension Method?
  2. Why do we use the Extension Method?
  3. Example of Extension Method.
  4. Rules to Create Extension Method.
  5. Create Extension Method.
  6. How to Use / Access Extension Method in Other Namespaces?
  7. Benefits Of Extension Method.

What are Extension Methods in C#?

Extension methods allow us to "add" methods to the existing class or types without modifying them, adding code, extending them, or recompiling the class. Extension Methods are like normal methods, but they are all special kinds of static methods. We can call the extension method in the same general way, and there is no difference in the way of accessing the method. The extension method features are enabled from C# 3.0.

Extension method

Why do we use the Extension Method?

In many situations, we need to call the same method or functionality at many places. Since extension methods are predefined methods having predefined properties without using Inheritance, we can extend the existing classes to add our own methods.

Example. Most of the time, we are in the position to call the extension method by knowing or without knowing this as an extension method. In our coding life, we keep using the extension methods regularly. We know very well that the .NET Framework comes with a set of predefined classes, functions, and properties. Okay, now let me show you the list of some extension methods used in our C# Language. The following is the extension method for a string. The extension method is loaded based on the datatype, class, collections, methods, and properties.

methods function

Rules to Create Extension Method in C#

Follow the below rules to create an extension method in your application.

  • Create a static visible class that will hold the extension method(s). Make sure that the class is visible to the other class / Namespace by applying the appropriate access modifier.
  • Create static Method(s) in the same Static Class with the same visibility level.
  • The extension Method uses the "this" keyword as the first parameter. The first parameter always specifies the type that the method operates on.
  • The extension method is written inside a static class, and the method is also defined as static. Though it is defined as a static method, it is still invoked on a particular instance.
  • An extension method should be in the same namespace as it is used, or you need to import the namespace of the class by a statement.
  • You can give any name for the class that has an extension method, but the class should be static.
  • If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called. Always make sure that the extension method already contains predefined keywords.
  • Keep in mind that we do not need to pass the first parameter because that denotes the type, however, we should pass the second parameter onwards to call the extension method.

How to Create Extension Method in C#?

First, we will go with a simple sample. Later, we will see how to provide access to other solutions/projects/clients. Let's move!

public static class ExtensionMethodClass
{
    public static bool IsGreaterThan5(this int input)
    {
        bool result = false;
        if (input > 5)
        {
            result = true;
        }
        return result;
    }
}

In the above code, we followed the rules that we mentioned in the class and defined an extension method as static with a public access modifier. We created a method "isGreaterThan5" in which doesn't exist the predefined keyword. So, we may use it for the extension method name. "This" keyword is used in the first parameter to mention this as an extension method. This is how the extension methods are created.

How to Use / Access Extension Method in Other Namespaces?

In the previous example, we saw how to invoke the extension method in our class. Now, we are going to see how to invoke the extension method as

  • Invoke in the Same Namespace
  • Invoke in Different Namespace

Let's see examples one by one to get a clear picture of this.

1. Invoke in the Same Namespace

Invoke in the same namespace' represents that the classes are presented within the same namespace with an extension method. It will be called by calling like other extension methods.

We have seen how to create an extension method and created the extension method in the name of "isGreaterThan5". Now, we will see how to call the extension method in our class. For a clear understanding, I am providing the screenshots.

invokesame namespace

using System;
namespace ExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Any Integer Value" + System.Environment.NewLine);
            int userInput = Convert.ToInt32(Console.ReadLine());
            bool result = userInput.IsGreaterThan5();
            Console.WriteLine("The result is " + result);
        }
    }
    public static class ExtensionMethodClass
    {
        public static bool IsGreaterThan5(this int input)
        {
            bool result = false;
            if (input > 5)
            {
                result = true;
            }
            return result;
        }
    }
}

Result

For more understanding, view the below image.

graphical representation

2. Invoke in Different Namespace

Now, we will see how to call the other namespace extension method in our class. Shall we move? For that, I am going to create one class library in the same solution.

Step 1. Create a new class library in the same solution.

class library

Step 2. Create Extension Method(s).

Here, I have created an extension method to change the first char to uppercase from a given string.

public static class Class1
{
    public static string FirstCharToUpper(string input)
    {
        if (String.IsNullOrEmpty(input))
        {
            throw new ArgumentException("ArgumentException");
        }
        return input.First().ToString().ToUpper() + input.Substring(1);
    }
}

Step 3. Refer to the class library in your class. Right-click on the respective class to add the extension method class reference.

reference1

Step 4. Select Respective Class Library.

Here, we are adding the saying that we are selecting the reference from within the solution.

reference2

In the below image, you can see that the HereExtensionMethodExist class library is added as a reference to our respective class.

respective class

How to call the invoke the extension method action into class?

Step 1. Add a namespace in the header.

using HereExtensionMethodExist;

Step 2. We don't need to create an object, or we cannot create an object for the extension method.

using System; // Include the System namespace for Console
namespace YourNamespace // Replace YourNamespace with the actual namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Your Name");
            string userStringInput = Console.ReadLine();
            string stringResult = Class1.FirstCharToUpper(userStringInput);
            Console.WriteLine(stringResult);
        }
    }
}

Here, Class1 is the Class Library Class, and the FirstCharToUpper is our Extension Method.

Now, see the complete code in our class.

Console.WriteLine("Enter Any Integer Value" + System.Environment.NewLine);
int userInput = Convert.ToInt32(Console.ReadLine());
bool result = userInput.IsGreaterThan5();
Console.WriteLine("The result is " + result);
// Other Namespace Extension Method
Console.WriteLine("Enter Your Name");
string userStringInput = Console.ReadLine();
string stringResult = Class1.FirstCharToUpper(userStringInput);
Console.WriteLine(stringResult);

Result

result

Now, you can see both the results by using two extension methods.

Benefits of extension methods

  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
  • If the class is sealed, then there is no concept of extending its functionality. For this, a new concept is introduced, in other words, extension methods.
  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.
  • And we can avoid code redundancy.

Summary

In this article, we learned how to create the extension method and all the ways we can access it.

I hope this was helpful to you. Your feedback and comments are always welcome.


Similar Articles