Menu
Coddy logo textTech

Extension Methods

Part of the Object Oriented Programming section of Coddy's C# journey — lesson 39 of 70.

Extension methods let you add new methods to existing types without modifying their source code or creating derived classes. They appear as if they're native methods of the type, making your code more readable and intuitive.

To create an extension method, define a static method in a static class, with the first parameter preceded by the this keyword:

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(' ').Length;
    }
}

Now you can call this method directly on any string:

string sentence = "Hello World Today";
int count = sentence.WordCount();  // 3

The this string str parameter tells the compiler this method extends the string type. When you call sentence.WordCount(), the compiler translates it to StringExtensions.WordCount(sentence) behind the scenes.

Extension methods can also accept additional parameters:

public static bool IsLongerThan(this string str, int length)
{
    return str.Length > length;
}

// Usage
bool result = "Hello".IsLongerThan(3);  // true

This technique is used extensively in LINQ, where methods like Where() and Select() are extension methods on IEnumerable. Extension methods are powerful for adding utility functions to types you don't control, keeping your code clean and expressive.

challenge icon

Challenge

Easy

Let's build a set of useful extension methods for integers that add convenient functionality you'd expect to have built-in. You'll create a static class containing extension methods that can be called directly on any integer, making your code more expressive and readable.

You'll organize your code across two files:

  • IntExtensions.cs: Create a static class called IntExtensions in the Utilities namespace. This class will contain extension methods that enhance the int type:
    • IsEven() - returns true if the number is even, false otherwise
    • Square() - returns the number multiplied by itself
    • IsInRange(int min, int max) - returns true if the number is between min and max (inclusive), false otherwise
    Remember that extension methods must be static methods in a static class, with the first parameter using the this keyword to specify which type you're extending.
  • Program.cs: In your main file, read an integer from input and demonstrate all three extension methods. Call each method directly on the integer as if it were a built-in method, then print the results.

You will receive three inputs:

  • A number to test (integer)
  • Minimum value for range check (integer)
  • Maximum value for range check (integer)

Print the output in this format:

Is {number} even? {True/False}
Square of {number}: {result}
Is {number} in range [{min}-{max}]? {True/False}

For example, if the inputs are 7, 5, and 10, the output should be:

Is 7 even? False
Square of 7: 49
Is 7 in range [5-10]? True

Notice how naturally you can write number.IsEven() and number.Square() - the extension methods feel like they've always been part of the integer type!

Cheat sheet

Extension methods allow you to add new methods to existing types without modifying their source code. They must be defined as static methods in a static class, with the first parameter preceded by the this keyword.

Basic extension method syntax:

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(' ').Length;
    }
}

Usage:

string sentence = "Hello World Today";
int count = sentence.WordCount();  // 3

The this keyword before the first parameter indicates which type is being extended. The compiler translates sentence.WordCount() to StringExtensions.WordCount(sentence).

Extension methods with additional parameters:

public static bool IsLongerThan(this string str, int length)
{
    return str.Length > length;
}

bool result = "Hello".IsLongerThan(3);  // true

Try it yourself

using System;
using Utilities;

class Program
{
    public static void Main(string[] args)
    {
        // Read inputs
        int number = Convert.ToInt32(Console.ReadLine());
        int min = Convert.ToInt32(Console.ReadLine());
        int max = Convert.ToInt32(Console.ReadLine());

        // TODO: Use the extension methods on 'number' and print the results
        // Call number.IsEven(), number.Square(), and number.IsInRange(min, max)
        // Print in the format:
        // Is {number} even? {True/False}
        // Square of {number}: {result}
        // Is {number} in range [{min}-{max}]? {True/False}

    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming