Junior — Middle
Can you explain what is meant by an extension method in programming?
sobes.tech AI
Answer from AI
Extension method in C# is a way to add a new method to an existing type without modifying the original source code of that type and without creating a new derived type. Such methods are declared as static in a static class, and the first parameter of the method is marked with the this keyword, indicating the type to which the method is added.
This is convenient when you need to extend the functionality of classes from libraries that you do not have access to modify.
Example of an extension method:
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
// Usage:
string s = null;
bool result = s.IsNullOrEmpty();
Here, IsNullOrEmpty appears as an instance method of a string, although it is actually a static extension method.