Originally published at https://allcoderthings.com/en/article/csharp-extension-methods
In C#, extension methods provide a way to add new methods to existing classes or structs without modifying their source code. These methods are actually defined inside a static class, and their first parameter specifies the extended type with the this keyword. Extension methods enhance functionality while keeping original types intact.
Basic Syntax
An extension method must always be defined inside a static class. Its first parameter is marked with this to specify the type it extends.
// Definition of an extension method
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string? text)
{
return string.IsNullOrEmpty(text);
}
}
class Program
{
static void Main()
{
string s1 = null;
string s2 = "Hello";
Console.WriteLine(s1.IsNullOrEmpty()); // True
Console.WriteLine(s2.IsNullOrEmpty()); // False
}
}
Here, the IsNullOrEmpty method is defined inside StringExtensions, but it can be used as if it were part of the string type.
Use Cases for Extension Methods
- Add new functionality to existing classes (e.g.,
string,DateTime). - Call common helper methods with a more natural syntax.
- Simplify fluent coding patterns such as LINQ.
Practical Examples
Extension methods make common operations more readable and convenient in daily coding.
// Extension methods for integers
public static class IntExtensions
{
// Is the number even?
public static bool IsEven(this int number) => number % 2 == 0;
// Is the number odd?
public static bool IsOdd(this int number) => number % 2 != 0;
}
class Program
{
static void Main()
{
int x = 10;
Console.WriteLine(x.IsEven()); // True
Console.WriteLine(x.IsOdd()); // False
}
}
Here, IsEven and IsOdd are defined as if they belonged to the int type. Any int variable can directly use these methods.
// Extension method for DateTime
public static class DateTimeExtensions
{
// Checks whether the given date falls on a weekend
public static bool IsWeekend(this DateTime dt)
=> dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;
}
class Program
{
static void Main()
{
DateTime today = DateTime.Now;
Console.WriteLine(today.IsWeekend() ? "Weekend" : "Weekday");
}
}
LINQ and Extension Methods
All LINQ methods are defined as extension methods. For example, Where, Select, and OrderBy are extension methods implemented for IEnumerable<T>.
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// Where is actually an extension method
var evens = numbers.Where(n => n % 2 == 0);
Console.WriteLine(string.Join(", ", evens)); // 2, 4, 6
Example: String Manipulation
Letβs define extension methods for performing checks and formatting on strings.
public static class TextExtensions
{
// Converts a string into title case (capitalize each word)
public static string ToTitleCase(this string text)
{
if (string.IsNullOrWhiteSpace(text)) return string.Empty;
return string.Join(" ",
text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(w => char.ToUpper(w[0]) + w.Substring(1).ToLower()));
}
// Checks whether a string contains any digits
public static bool ContainsDigit(this string text)
{
return text.Any(char.IsDigit);
}
}
class Program
{
static void Main()
{
string input = "hello world 2025";
Console.WriteLine(input.ToTitleCase()); // "Hello World 2025"
Console.WriteLine(input.ContainsDigit()); // True
}
}
Advantages
- Improves readability with natural syntax.
- Allows reusing existing classes without creating new ones.
- Adds new features without altering existing types.
- Centralizes helper methods in a single place.
TL;DR
- Extension methods are a way to add new functionality to existing classes.
- They are defined inside a
staticclass; the first parameter withthisspecifies the extended type.- LINQ methods are the most common examples of extension methods.
- They improve code readability and flexibility.
Top comments (0)