C# Medium · Lesson 1 · On the house

Extension methods

Add methods to types you don't own with static classes and the this modifier. Lesson 1 is free — on the house.

Lessons · C# Medium · Lesson 1 of 10 · On the house

Extension methods

Add methods to types you don't own with static classes and the this modifier.

Illustration for C#
Lesson 1 is on the house.

An extension method is a static method in a non-nested, non-generic static class whose first parameter carries this: public static bool IsEven(this int n) => n % 2 == 0;.

Call it like an instance method: 4.IsEven(). The compiler rewrites it to IntExt.IsEven(4).

The namespace holding the static class must be imported with using, or the method is invisible.

A real instance method with the same signature always wins over an extension, so extensions can't override behavior.

LINQ itself is a set of extension methods on IEnumerable<T>; write your own the same way, e.g. this IEnumerable<T> src with a generic <T> on the method.

extensions

Console.WriteLine(4.IsEven());
Console.WriteLine("hello world".WordCount());
int[] xs = [3, 1, 4, 1, 5];
Console.WriteLine(string.Join(",", xs.EveryOther()));

static class Ext
{
    public static bool IsEven(this int n) => n % 2 == 0;
    public static int WordCount(this string s) =>
        s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
    public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> src)
    {
        int i = 0;
        foreach (var x in src)
            if (i++ % 2 == 0) yield return x;
    }
}
Match this when you type.

Quiz

Which keyword marks the first parameter of an extension method?

Quiz

What kind of class must hold extension methods?

Quiz

If a type has an instance method with the same signature as an extension, which is called?

Quiz

What does xs.EveryOther() print for 3,1,4,1,5?

Check

Match the still for: Extension methods.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.