0Pricing
C# Academy · Lesson

Defining Extension Methods

Write static methods with the this modifier.

What Is an Extension Method?

An extension method lets you add new methods to an existing type without modifying it or creating a derived type. You call it as if it were an instance method, but it is really a special static method.

Extensions are perfect when you do not own the source code of a type (like string or int) but want to give it a convenient new behavior.

The Three Requirements

To declare an extension method you need: a static class, a static method, and a first parameter marked with the this keyword. The this parameter names the type you are extending.

using System;

public static class StringExtensions
{
    public static int WordCount(this string text)
    {
        if (string.IsNullOrWhiteSpace(text)) return 0;
        return text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

public class Program
{
    public static void Main()
    {
        string sentence = "the quick brown fox";
        Console.WriteLine(sentence.WordCount());
    }
}

All lessons in this course

  1. Defining Extension Methods
  2. Extending Interfaces and Generics
  3. Extension Method Resolution
  4. Designing Good Extensions
← Back to C# Academy