Extension methods in C# with examples

In C#, an extension method is a special kind of static method that is defined in a static class but can be called on an instance of a type as if it were an instance method of that type. Extension methods are a way to add methods to existing types without creating a new derived type, modifying the original type, or using any kind of reflection.

In this article, we will discuss extension methods in C# through several examples.

Extension Methods in C#
Extension Methods in C#

C# Extension Methods

Extension methods were introduced in C# 3.0, allowing developers to add new methods to existing classes or structures without having to create new derived types, recompile code, or modify the original types.

Important Points about extension methods

Following are some key points about extension methods in C#.

  • In C#, an extension method is a static method that is defined in a static class and is used to extend the functionality of an existing type without modifying its code.
  • It is not possible to override extension methods using the override keyword, as they do not support method overriding.
  • We can add extension methods to the sealed classes as well.
  • It is useful for adding a custom method to a class that was not originally included in it.
  • The this keyword is used to bind the extension method to an instance of the class it is extending.
  • The first parameter of the extension method must be of the type being extended and must be preceded by the this keyword.
  • It is not possible to use extension methods with fields, properties, or events.

When to use extension methods in C#?

In C#, extension methods are useful for adding new methods to an existing class or struct without modifying the source code or requiring permission to make changes to the original type. They are particularly helpful when the original class or struct contains several methods but the source code is not available or it is not possible to make changes to it.

Example: Extension method

Here is an example of an extension method that adds a ToUpperFirstLetter() method to the string type:

using System;
using System.Globalization;
namespace ExtensionMethodExample
{
    public static class StringExtensions
    {
        public static string ToUpperFirstLetter(this string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }

            // Return first letter as Capital from string
            string str = new CultureInfo("en-US").TextInfo.ToTitleCase(s);
            return str;
        }
    }
   class Program
    {
        static void Main(string[] args)
        {
            string name = "shekh ali";
           // Calling Extension method
            Console.WriteLine($" Name:{name.ToUpperFirstLetter()}"); //  Name:Shekh Ali
            Console.ReadKey();
        }
    }
}

In the above example, we are calling the ToUpperFirstLetter() extension method on any string like the name.

Example 2:

We can create a class called MyClass that includes Method1 and Method2, and then add Method3 to it without altering the original code. To do this, we can create a new static class called MyExtensionClass that includes Method3 and extend MyClass using this static class. This will allow us to use Method3 as if it were part of MyClass.

Here is a sample program showing how to use extension methods in C#:

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

In the image below, we can see that the extension method Method3 can be accessed using an object of the original class called MyClass.

extension method in c#
Extension method in c#

In the IntelliSense feature of Visual Studio, extension methods are marked with a down arrow symbol to help developers distinguish them from regular class methods.

Add extension method in string type in C#

Here is a program that demonstrates how to add an extension method to the 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

The above program shows how to use extension methods to add new functionality to the string data type. In this case, the extension method is a static method defined in a static class. The first parameter of the method is the string data type that is being extended, which is identified by the this keyword. Extension methods allow us to add new behavior to existing data types without modifying the original code.

C# Extension methods in LINQ

Extension methods are widely used in C# .NET and LINQ. These are the two common frameworks in which they are utilized. C# is particularly well-suited for working with extension methods as they allow developers to add new functionality to existing data types without modifying the original code, and are a useful tool for increasing the efficiency and flexibility of their code.

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

Example:

Here is a simple program that demonstrates the use of extension methods 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();
          
        }
    }
}
// OutPut:
// 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.

Advantage of extension methods in C#

  • One of the primary benefits of extension methods is that they allow developers to add new behavior (methods) to existing classes without using inheritance.
  • Although sealed classes cannot be extended through inheritance, extension methods provide a way for developers to add new methods to them. This allows developers to add new functionality to sealed classes, even though they cannot be subclassed.
  • A developer can add new methods in the existing class without modifying the original source code of the existing type.
  • The extension method Increases code efficiency and flexibility.
  • It makes code more readable and maintainable.
  • An extension method can be used to extend a wide range of data types, including those from the .NET framework, third-party libraries, and custom types

Are extension methods a good way to add new functionality to a class?

Extension methods can be a convenient way to add new functionality to a class, especially if you do not have the source code for the class or if you want to add the functionality to multiple classes without creating a new derived type.

  • One limitation of extension methods is that they are not as flexible as regular methods. Extension methods are static methods that are called as if they were instance methods, but they do not have access to the instance data of the object they are called on. This means that extension methods cannot modify the state of the object they are called on, and they cannot access private data or methods of the object.
  • Another limitation of extension methods is that they can be difficult to discover and use. Because extension methods are defined in a separate class, it can be difficult for other developers to find them and understand how they work. This can make it harder to use extension methods effectively, especially in larger projects.
  • Overall, extension methods can be a useful way to add new functionality to a class, but they are not always the best choice. It is important to consider their limitations and the context in which they will be used before deciding to use them.

Conclusion:

In this article, we covered the basics of extension methods in C# and provided examples of their use. I hope you found the information and examples helpful. If you have any questions or comments, please let me know in the section below.

FAQ

Here are some answers to frequently asked questions about extension methods in C#:

Q: Are extension methods limited to extending a specific type?

A: No, we can create extension methods that extend any type, including interfaces and value types. We can also create extension methods that extend multiple types by using generic type parameters.

Q: Can extension methods be used in the same way as instance methods in C#?

A: Yes, extension methods can be used in the same way as instance methods, with a few limitations. You can pass extension methods as parameters, return them as values, and use them in LINQ queries. However, you cannot override extension methods or use them as virtual methods.

Q: Are extension methods slower than instance methods?

A: In general, extension methods are slightly slower than instance methods because they require an extra method call. However, the difference in performance is usually not significant unless you are calling the extension method many times in a loop.

Recommended Articles

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments