0Pricing
C# Academy · Lesson

Defining Extension Methods

Write static methods with the this modifier.

Defining Extension Methods is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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());
    }
}

Calling It Like an Instance Method

Even though WordCount is static, you call it as sentence.WordCount(). The compiler rewrites that call into StringExtensions.WordCount(sentence) behind the scenes.

using System;
using System.Linq;

public static class StringExtensions
{
    public static string Repeat(this string text, int times)
    {
        return string.Concat(Enumerable.Repeat(text, times));
    }
}

public class Program
{
    public static void Main()
    {
        // These two lines do exactly the same thing
        Console.WriteLine("ab".Repeat(3));
        Console.WriteLine(StringExtensions.Repeat("ab", 3));
    }
}

The this Parameter Receives the Instance

The value to the left of the dot becomes the this parameter. You can add more parameters after it, and callers pass those normally.

using System;

public static class IntExtensions
{
    public static bool IsBetween(this int value, int low, int high)
    {
        return value >= low && value <= high;
    }
}

public class Program
{
    public static void Main()
    {
        int age = 25;
        Console.WriteLine(age.IsBetween(18, 65));
        Console.WriteLine(10.IsBetween(1, 5));
    }
}

Extending Your Own Types

Extensions are not just for library types. You can extend your own classes too, which is handy for keeping a clean core type while adding helper behaviors elsewhere.

using System;

public class Money
{
    public decimal Amount { get; }
    public Money(decimal amount) { Amount = amount; }
}

public static class MoneyExtensions
{
    public static string ToUsd(this Money m) => "$" + m.Amount.ToString("0.00");
}

public class Program
{
    public static void Main()
    {
        var price = new Money(19.5m);
        Console.WriteLine(price.ToUsd());
    }
}

Extensions Cannot Access Private Members

An extension method is just a static method in another class, so it can only use the public (or internal, when in the same assembly) surface of the type. It cannot reach into private fields.

using System;

public class Counter
{
    private int _count;
    public int Value => _count;
    public void Increment() => _count++;
}

public static class CounterExtensions
{
    // Can only use public members like Value and Increment
    public static bool IsZero(this Counter c) => c.Value == 0;
}

public class Program
{
    public static void Main()
    {
        var c = new Counter();
        Console.WriteLine(c.IsZero());
        c.Increment();
        Console.WriteLine(c.IsZero());
    }
}

Chaining Extension Methods

Because each extension returns a value, you can chain them into a fluent pipeline. This reads top to bottom and is the style LINQ uses.

using System;

public static class TextExtensions
{
    public static string Shout(this string s) => s.ToUpper();
    public static string Bang(this string s) => s + "!";
}

public class Program
{
    public static void Main()
    {
        string result = "hello".Shout().Bang();
        Console.WriteLine(result);
    }
}

Null and Extension Methods

Unlike a real instance call, an extension method can run even when the receiver is null, because nothing is dereferenced until your code touches it. This lets you write null-safe helpers.

using System;

public static class StringExtensions
{
    public static bool IsBlank(this string text)
    {
        // text may be null here, and that is fine
        return string.IsNullOrWhiteSpace(text);
    }
}

public class Program
{
    public static void Main()
    {
        string nothing = null;
        Console.WriteLine(nothing.IsBlank());
        Console.WriteLine("x".IsBlank());
    }
}

Instance Methods Win Over Extensions

If a real instance method with a matching signature exists, the compiler always prefers it over an extension method. Extensions only fill gaps the type does not already cover.

using System;

public static class Ext
{
    // This will be ignored because string already has ToString()
    public static string ToString(this string s, int n) => s + n;
}

public class Program
{
    public static void Main()
    {
        // Resolves to the built-in instance ToString(), not the extension
        Console.WriteLine("value: " + "abc".ToString());
    }
}

A Practical Helper Library

Grouping related extensions in one static class creates a tidy utility library. Here is a small numeric helper class you might reuse across a project.

using System;

public static class NumberExtensions
{
    public static bool IsEven(this int n) => n % 2 == 0;
    public static int Squared(this int n) => n * n;
    public static double Percent(this int n) => n / 100.0;
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(4.IsEven());
        Console.WriteLine(5.Squared());
        Console.WriteLine(50.Percent());
    }
}

Try It Yourself

Combine what you learned: one static class with several focused extensions, called fluently. This is exactly how everyday helper libraries are built.

using System;

public static class StringExtensions
{
    public static string Capitalize(this string s)
        => string.IsNullOrEmpty(s) ? s : char.ToUpper(s[0]) + s.Substring(1);
    public static string Surround(this string s, char c) => c + s + c;
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("hello".Capitalize().Surround('*'));
    }
}

Quick Check

Test your understanding of extension method declaration.

Recap

You learned that an extension method is a static method in a static class whose first parameter uses this. It is called with instance syntax but compiles to a normal static call.

  • Three requirements: static class, static method, this first parameter.
  • Only public members are reachable.
  • Instance methods always take priority.
  • Extensions can chain and can even run on null receivers.

Frequently asked questions

Is the “Defining Extension Methods” lesson free?

Yes — the full text of “Defining Extension Methods” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Defining Extension Methods”?

Write static methods with the this modifier. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Defining Extension Methods” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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