C# extension methods with examples | use of [extension methods] in LINQ

In this article, we will discuss about the extension methods in C# with multiple examples.

C# extension methods
C# extension methods.

What is the extension method in C#?

The extension method was introduced in C# 3.0, Which allows a developer to add new methods in the existing class or structure without creating a new derived type, recompiling the code, or modifying the original type.

When to use extension methods in C#?

In C#, extension methods are very useful when we wanted to add a new method in the existing class or struct which already contains few methods but we don’t have the source code or permissions to do changes in the existing type.

Let us discuss this concept with the help of the following example.

Now let’s create a class “MyClass” which contains two methods (Method1, Method2) and add a new method (Method3) without doing any code changes in the existing class.

Now to add an extension method, we have to create a new static class “MyExtensionClass” with the new method which we want to add to the existing class “MyClass“, now we will bind this static class with the existing class.
After binding, we will able to see that the existing class can access the newly added method.

following is the program snippet.

using System;
namespace ExtensionMethodExample
{  // Existing class
    public class MyClass
    {
        public void Method1() => Console.WriteLine("Method1");
        public void Method2() => Console.WriteLine("Method2");
    }
    // static class
    public static class MyExtensionClass
    {     
        // Extension Method
            public static void Method3(this MyClass myClass)
            {
               Console.WriteLine("Extension Method3");
            }      
    }
  
    class Program
    {
        static void Main(string[] args)
        {
            // Creating object of the existing class
            MyClass myClass = new MyClass();
            myClass.Method1();
            myClass.Method2();
           // extension method is accessible in the object of the existing class.
            myClass.Method3();
            Console.ReadKey();
        }
    }
}
// Output
// Method1
// Method2
// Extension Method3

Here in the below image, we can see that the extension method “Method3” is accessible by the object of an existing class.

extension method in c#
extension method in c#

The extension methods have a special symbol (down arrow) in intellisense of the visual studio,
so that a developer can easily differentiate between class methods and extension methods.

Add extension method in string type in C#

Let’s create a program to see how to add extension method in existing string type.

using System;
namespace ExtensionMethodExample
{   
    // static class
    public static class MyExtensionClass
    {     
        // Adding extension method in string type.

            public static int TotalWordCount(this String str)
            {
                return str.Split(new char[] {'/', ' ', '.', '?' },
                       StringSplitOptions.RemoveEmptyEntries).Length;
            }      
    }
  
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World";
            int totalWords =  str.TotalWordCount();
            Console.WriteLine($"str = {str}");
            Console.WriteLine($"Total Words = { totalWords}");
            Console.ReadKey();
        }
    }
}

//Output:
// str = Hello World
// Total Words = 2

Here in the above extension methods program, we can see that it simply gives us the ability to extend a string data type in our program. In the simplest terms possible, the extension method defines a static method in a static class. The method then identifies the data type that is being extended as the very first parameter in the method by identifying the “this” keyword that is placed in front of it.

C# [Extension methods] in LINQ

Extension methods are very common in the world of computer programming, and whether a developer uses them in C# .NET or LINQ, they can get a great deal of work done with it. In fact, C# is one of the only languages to inherently allows a developer to use extension methods with proficiency.

LINQ’s standard query operators ( such as Select, Where, Count, Contains, First, FirstOrDefault, Min, Max, Sum, etc. ) are implemented in Enumerable class as extension methods on the IEnumerable interface.

In spite of the Where() method in LINQ not belonging to the List<T> class, we are still able to use it through the List<T> class in the below program.
This is possible because Where() method is implemented as an extension method in the IEnumerable interface, and List<T> further implements the IEnumerable interface.

Lets create a simple program where we will use extension method in LINQ.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ExtensionMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //List of numbers
            List<int> Numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            
            // Here, Where() method is implemented as extension method.
            IEnumerable<int> EvenNumbers = Numbers.Where(num => num % 2 == 0);
            
            //Print even numbers
            foreach (int number in EvenNumbers)
                Console.WriteLine(number);

                Console.ReadKey();
          
        }
    }
}
// OuPut
// 2
// 4
// 6
// 8
// 10
extension methods in LINQ
extension methods in LINQ

In the above image, we can see that Where() is an extension method and belongs to IEnumerable<T> interface.

Important Points about extension methods

Following are few important points about the extension method in C#.

    • An extension method is a static method and must be defined in a static class.
    • Extension methods cannot be used to override using override keywords as it does not support method overriding.
    • The extension methods can also be added in the sealed class.
    • this keyword is used for the binding extension method, Here MyClass is the existing class name in which you want to bind, and “myClass” is the parameter name.
      public static void Method3(this MyClass myClass)
    • We cannot apply the extension methods concepts to fields, properties, or events.
    • The first parameter in the extension method must be of the type for which the extension method is applicable, preceded by this keyword.

Advantage of extension methods in C#

The main advantage of the extension method is to allow the existing class to be extended without using inheritance.
A sealed class cannot be extended as it does not support inheritance, the extension method allows a developer to add a new method in the sealed class as well.
A developer can add new methods in the existing class without modifying the original source code of the existing type.

Conclusion:

In this article, we learned about the extension methods in C# with examples. I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.

Thanks for visiting.

Leave a Reply