Letβs go through extension methods in C# β a way to add new methods to existing types without modifying them.
π 1. What Are Extension Methods?
-
An extension method allows you to βextendβ an existing class or interface with a new method.
-
Useful for adding functionality to built-in types or third-party classes.
-
Declared as static methods in a static class.
π 2. Basic Syntax
public static class StringExtensions
{
public static bool IsCapitalized(this string str)
{
if (string.IsNullOrEmpty(str)) return false;
return char.IsUpper(str[0]);
}
}
-
this string str
β indicates extension for thestring
type -
Can now call
.IsCapitalized()
on any string
π 3. Using Extension Methods
string name = "Alice";
bool result = name.IsCapitalized();
Console.WriteLine(result); // True
- Looks like a normal method of the class, but itβs defined externally
π 4. Extension Methods with Parameters
public static class IntExtensions
{
public static bool IsDivisibleBy(this int number, int divisor)
{
return number % divisor == 0;
}
}
int num = 10;
Console.WriteLine(num.IsDivisibleBy(5)); // True
Console.WriteLine(num.IsDivisibleBy(3)); // False
- Extension methods can take additional parameters just like regular methods
π 5. Extension Methods with LINQ
-
LINQ uses extension methods extensively
-
Example:
Where()
,Select()
,OrderBy()
are all extension methods forIEnumerable<T>
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0); // LINQ extension
π 6. Rules for Extension Methods
-
Must be declared in a static class
-
Must be static method
-
First parameter specifies the type being extended with
this
-
Cannot override existing instance methods
π 7. Advantages
-
Add methods to existing classes without inheritance or modifying original code
-
Makes code more readable and fluent
-
Essential for fluent interfaces and LINQ operations
π 8. Summary Table
Feature | Description |
---|---|
Declaration | public static class , public static method |
this keyword | Marks the type being extended |
Usage | Call as if itβs an instance method |
Benefits | Adds functionality without modifying original class, improves readability |
Common Use Case | LINQ methods, helper methods for built-in types |
β Tip:
-
Use extension methods to add small helper functions to classes you cannot modify
-
Avoid adding too many unrelated methods to keep the API clean