Extension methods in C#

Extension methods in C# are a very cool feature, which allows you easily extend already-defined functionality. Find out more by reading this post.

What are extension methods in C#

Programmers often have to use external libraries to do their job. But what if you need to add some small functionality, which relates specifically to your application domain? You don’t have to edit the 3rd party library source code and compile it again. This is where extension methods comes to the rescue. They can add additional functionality to already compiled types, including external libraries or built-in .NET objects. For instance, you can extend the string type with a method checking if a value can be successfully converted into an integer:

C#
public static class StringExtensions
{
    public static bool IsNumber(this string value)
    {
        return int.TryParse(value, out int result);
    }
}

The IsNumber method is now available for the whole string type. Hence, you may use it on every string value, like this:

C#
string firstValue = "1";
string secondValue = "a";
Console.WriteLine(firstValue.IsNumber());
Console.WriteLine(secondValue.IsNumber());

And the result is:

Extension methods in C# - simple string extension
Extension methods in C# – simple string extension

Rules for defining an extension method

There are simple rules you must follow to define extension methods in C#. This ruleset is required for the compiler to properly understand that you are defining an extension. Otherwise, it will just consider it as an ordinary method. What are the rules?

  • Firstly all extension method must be defined in a static class. You can group your extensions in different classes for each type. For instance – ListExtensions, StringExtensions, SomeExternalLibraryExtensions and so on.
  • Since the class is static all of its methods are also static.
  • use this {type} as a first argument to the method. This will tell the compiler which type exactly you want to extend. For instance public static bool IsNumber(this string value).

Generic extension methods

You can make your extension methods generic, without any issues, as long as you are following the rules. There is nothing different, than a standard generic method declaration. For instance:

C#
public interface IPerson
{
    bool IsStudent { get; }

    string Name { get; }
}

public class Teacher : IPerson
{
    public Teacher(string name)
    {
        this.Name = name;
        this.IsStudent = false;
    }

    public bool IsStudent { get; }

    public string Name { get; private set; }
}

public class Student : IPerson
{
    public Student(string name)
    {
        this.Name = name;
        this.IsStudent = true;
    }

    public bool IsStudent { get; }

    public string Name { get; private set; }
}

public static class SchoolExtensions
{
    public static IEnumerable<T> GetStudents<T>(this IEnumerable<T> items)
        where T : IPerson
    {
        return items.Where(p => p.IsStudent);
    }
}

In this example, there are a Student and a Teacher, which are both IPerson. The extension method is over a collection of IPerson, and it filters the students. Use the code:

C#
var firstPerson = new Teacher("John");
var secondPerson = new Student("Peter");
var persons = new List<IPerson>() { firstPerson, secondPerson };
var students = persons.GetStudents();
foreach (var student in students)
{
    Console.WriteLine(student.Name);
}

And the result is:

Extension methods in C# - generic extension
Extension methods in C# – generic extension