MSDN Documentation

Microsoft Developer Network

C# Extension Methods

Extension methods enable you to "add" methods to existing types without actually modifying them. This is achieved by defining a static method in a static class. The first parameter of the extension method must be of the type that the method extends, and it must be preceded by the this keyword.

Defining an Extension Method

Consider a scenario where you want to add a method to the built-in string class to easily reverse it.

Example: StringExtensions.cs
namespace MyExtensions
{
    public static class StringExtensions
    {
        public static string ReverseString(this string str)
        {
            char[] charArray = str.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
    }
}

Using an Extension Method

Once defined, you can call the extension method on an instance of the type as if it were a member of that type. Make sure to import the namespace containing the extension method.

Example: Program.cs
using System;
using MyExtensions; // Import the namespace

public class Program
{
    public static void Main(string[] args)
    {
        string message = "Hello, World!";
        string reversedMessage = message.ReverseString(); // Calling the extension method

        Console.WriteLine($"Original: {message}");
        Console.WriteLine($"Reversed: {reversedMessage}");
        // Output:
        // Original: Hello, World!
        // Reversed: !dlroW ,olleH
    }
}

Key Concepts and Benefits

Limitations

When to Use Extension Methods

Example: Extension Methods for Collections

Extension methods are particularly useful for collections and LINQ.

Example: CollectionExtensions.cs
using System.Collections.Generic;
using System.Linq;

namespace MyExtensions
{
    public static class CollectionExtensions
    {
        public static int CountItems<T>(this IEnumerable<T> collection)
        {
            return collection.Count();
        }

        public static bool IsEmpty<T>(this IEnumerable<T> collection)
        {
            return !collection.Any();
        }
    }
}
Example: Using Collection Extensions
using System;
using System.Collections.Generic;
using MyExtensions;

public class DataProcessing
{
    public static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        List<string> words = new List<string>();

        Console.WriteLine($"Number count: {numbers.CountItems()}");
        Console.WriteLine($"Is number list empty? {numbers.IsEmpty()}");

        Console.WriteLine($"Word count: {words.CountItems()}");
        Console.WriteLine($"Is word list empty? {words.IsEmpty()}");
    }
}