Extension Methods in C#

From the C# Programming Language cheat sheet · Extension Methods and Nullable Types · verified Jul 2026

Extension Methods

Adding methods to existing types

csharp
// Extension method
public static class StringExtensions
{
    public static bool IsValidEmail(this string email)
    {
        return email?.Contains("@") ?? false;
    }
}

// Usage
string email = "test@example.com";
bool valid = email.IsValidEmail();

// Nullable types
int? nullableInt = null;
string? nullableString = null;

// Null operators
int value = nullableInt ?? 0; // Null coalescing
string length = nullableString?.Length.ToString() ?? "0";
💡 Extension methods must be in static classes with static methods
⚡ First parameter with this keyword defines extended type
📌 Null-conditional operator (?.) safely accesses members
🟢 Nullable reference types help catch null issues at compile time
Back to the full C# Programming Language cheat sheet