Custom Extension Method In C#

Introduction

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

Prerequisites
  • Visual Studio
  • Basics knowledge of C#
Article flow 
  1. What is Extension Method
  2. Why do we use 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 Namespace
  7. Benefits Of Extension Method 
Extension Methods

Extension methods allow us to "add" methods to the existing class or types without modifying it or adding code or extending it or recompiling the class.
 
Extension Methods are like normal methods but they are all special kind of static method. 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.

Why do we use 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 for Extension Method

Most of the time, we are in the position to call the extension method by knowing or without knowing this as extension methods. 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.

 
Rules to create Extension Method

Follow the below rules to create an extension method in your application.
  1. Create a static visible class which will hold the extension method(s). Make sure that the class is visible to the other class / Namespace by applying the appropriate access modifier.

  2. Create static Method(s) in the same Static Class with the same visibility level.

  3. Extension Method uses the "this" keyword as the first parameter. The first parameter always specifies the type that the method operates on.

  4. 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.

  5. 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 using statement.

  6. You can give any name for the class that has an extension method but the class should be static.

  7. 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.

  8. 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.
Create Extension Method

First, we will go with s simple sample. Later, we will see how to provide access to other solutions/projects/clients. Let's move!
  1. public static class ExtensionMethodClass {  
  2.     public static bool isGreaterThan5(this int input) {  
  3.         bool result = false;  
  4.         if (input > 5) {  
  5.             result = true;  
  6.         }  
  7.         return result;  
  8.     }  
  9. }  
In the above code, we followed the rules that we mentioned in the class and defined an extension method as static with public access modifier. We created a method "isGreaterThan5" in which doesn't exist the predefined keyword. So, we may use it for 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 Namespace
 
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 Same Namespace
  • Invoke in Different Namespace
Let's see examples one by one to get a clear picture about this.
 
Invoke in the Same Namespace
 
"Invoke in same namespace' represents that the classes are presented within the same namespace with extension method. It will be called by calling like other extension methods. 
 
We have seen how to create 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 clear understanding, I am providing the screenshots.
 
 
  1. namespace ExtensionMethod {  
  2.     class Program {  
  3.         static void Main(string[] args) {  
  4.             Console.WriteLine("Enter Any Integer Value" + System.Environment.NewLine);  
  5.             int userInput = Convert.ToInt32(Console.ReadLine());  
  6.             bool result = userInput.isGreaterThan5();  
  7.             Console.WriteLine("The result is " + result);  
  8.         }  
  9.     }  
  10.     public static class ExtensionMethodClass {  
  11.         public static bool isGreaterThan5(this int input) {  
  12.             bool result = false;  
  13.             if (input > 5) {  
  14.                 result = true;  
  15.             }  
  16.             return result;  
  17.         }  
  18.     }  
Result



For more understanding, view the below image.
 
 
 
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. 
 
 
 
Step 2

Create Extension Method(s)
 
Here, I have created an extension method to change the first char to uppercase from a given string.
  1. public static class Class1 {  
  2.     public static string FirstCharToUpper(string input) {  
  3.         if (String.IsNullOrEmpty(input)) {  
  4.             throw new ArgumentException("ArgumentException");  
  5.         }  
  6.         return input.First().ToString().ToUpper() + input.Substring(1);  
  7.     }  
  8. }  
Step 3

Refer to the class library into your class. Right click on the respective class to add the extension method class reference.
 
  
 
Step 4

Select Respective Class Library 
 
Here, we are adding the saying that as we are selecting the reference from within the solution.
 
 
 
In the below image, you can see that the HereExtensionMethodExist class library is added as reference to our respective class.
 
 
 
Okay! now let's see how to call the invoke the extenstion method action into our class
 
Step 1

Add a namespace in header
  1. using HereExtensionMethodExist;    
Step 2

We don't need to create object  or we cannot create object for extension method  
  1. //Other Namespace Extension Method  
  2. Console.WriteLine("Enter Your Name");  
  3. string userStringInput = Console.ReadLine();  
  4. string stringResult = Class1.FirstCharToUpper(userStringInput);  
  5. 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.
  1. Console.WriteLine("Enter Any Integer Value" + System.Environment.NewLine);  
  2. int userInput = Convert.ToInt32(Console.ReadLine());  
  3. bool result = userInput.isGreaterThan5();  
  4. Console.WriteLine("The result is " + result);  
  5. //Other Namespace Extension Method  
  6. Console.WriteLine("Enter Your Name");  
  7. string userStringInput = Console.ReadLine();  
  8. string stringResult = Class1.FirstCharToUpper(userStringInput);  
  9. Console.WriteLine(stringResult);  
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 than there in 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.