C# Interview Question #81
What are extension methods in C#?
Advanced C# Language Features Mid-Level Intermediate
Quick Interview Answer
Extension methods allow developers to add method-like functionality to an existing type without modifying that type or creating a derived class.
Detailed Explanation
Extension methods allow developers to add method-like functionality to an existing type without modifying that type or creating a derived class.
An extension method is declared as a static method inside a static class, and its first parameter uses the this modifier to identify the type being extended.
They are widely used throughout .NET. LINQ methods such as Where, Select, and OrderBy are extension methods. Extension methods are useful for reusable helper behavior, but they should not be used to hide complex business logic or create unclear APIs.
Code Example
public static class StringExtensions
{
public static bool IsNotEmpty(this string? value)
{
return !string.IsNullOrWhiteSpace(value);
}
}
bool valid = "C#".IsNotEmpty();