0
0
C Sharp (C#)programming~5 mins

Extension methods for built-in types in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Extension methods let you add new actions to existing types like strings or numbers without changing their original code.

You want to add a helpful action to a string, like checking if it has only letters.
You want to add a new way to work with numbers, like checking if a number is even.
You want to keep your code clean by adding small reusable actions to built-in types.
You want to use new features on types you cannot change, like types from the system library.
Syntax
C Sharp (C#)
public static class ClassName
{
    public static ReturnType MethodName(this Type parameter, other parameters...)
    {
        // method body
    }
}

The this keyword before the first parameter tells C# this is an extension method.

Extension methods must be inside a static class and be static themselves.

Examples
This adds an IsAllLetters method to strings to check if all characters are letters.
C Sharp (C#)
public static class StringExtensions
{
    public static bool IsAllLetters(this string str)
    {
        foreach (char c in str)
            if (!char.IsLetter(c)) return false;
        return true;
    }
}
This adds an IsEven method to integers to check if a number is even.
C Sharp (C#)
public static class IntExtensions
{
    public static bool IsEven(this int number)
    {
        return number % 2 == 0;
    }
}
Sample Program

This program adds a new method to strings to check if they contain only letters. It then tests two words and prints the results.

C Sharp (C#)
using System;

public static class StringExtensions
{
    public static bool IsAllLetters(this string str)
    {
        foreach (char c in str)
            if (!char.IsLetter(c)) return false;
        return true;
    }
}

public class Program
{
    public static void Main()
    {
        string word1 = "Hello";
        string word2 = "Hello123";

        Console.WriteLine($"{word1} is all letters: {word1.IsAllLetters()}");
        Console.WriteLine($"{word2} is all letters: {word2.IsAllLetters()}");
    }
}
OutputSuccess
Important Notes

Extension methods look like normal methods when you use them, but they are static methods behind the scenes.

You can add extension methods to any type, including built-in types like string and int.

Extension methods cannot access private members of the type they extend.

Summary

Extension methods add new actions to existing types without changing them.

They must be static methods inside static classes, with this before the first parameter.

They help keep code clean and let you add useful features to built-in types.