Extensionmethods allow you to "add" methods to existing types (classes, structs, interfaces)
without modifying their source code or creating a derived type.
They are a type of syntactic sugar in C# that enables more natural, readable code.
Key Features
Declared as static methods in a static class
First parameter is prefixed with the this keyword
Can be called using instance method syntax
Example: Creating an Extension Method
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string input)
{
return string.IsNullOrEmpty(input);
}
}
Now you can use it like this:
string name = "";
bool result = name.IsNullOrEmpty(); // Looks like a real method of string!
How It Works Behind the Scenes
The compiler converts this:
name.IsNullOrEmpty();
Into this:
StringExtensions.IsNullOrEmpty(name);
So the method is still static, just looks like an instance method.
Practical Example: List Extensions
public static class ListExtensions
{
public static void PrintAll<T>(this List<T> list)
{
foreach (var item in list)
Console.WriteLine(item);
}
}
Usage:
var nums = new List<int> { 1, 2, 3 };
nums.PrintAll(); // Extension method used like a built-in method
When to Use Extension Methods
Use Case
Use Extension Method?
Want to add methods to built-in types
Yes
Cannot modify source of the type
Yes
Need to enhance readability or reuse
Yes
Need polymorphism or override behavior
No (use inheritance instead)
Limitations
Cannot override existing methods
Cannot access private members of the target type
Only resolved at compile time, no virtual dispatch
Common Uses
LINQ (e.g. Where, Select, ToList)
Fluent APIs
Utility functions for built-in or library types
Example: LINQ Extension Method
var even = numbers.Where(n => n % 2 == 0);
Here, Where() is an extension method defined in
System.Linq.Enumerable.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
They are a type of syntactic sugar in C# that enables more natural, readable code.
Key Features
thiskeywordExample: Creating an Extension Method
Now you can use it like this:
How It Works Behind the Scenes
The compiler converts this:
Into this:
So the method is still static, just looks like an instance method.
Practical Example: List Extensions
Usage:
When to Use Extension Methods
Limitations
Common Uses
Where,Select,ToList)Example: LINQ Extension Method
Here,
Where()is an extension method defined inSystem.Linq.Enumerable.