Extension Methods in C#
In C#, an extension method is a static method that can be added to an existing class or interface without modifying the original code. It is a way to extend the functionality of a class without inheriting from it, recompiling, or modifying the original class.
To create an extension method, you need to define a static class and a static method within that class.
The first parameter of the method should be preceded by the “this” keyword followed by the type that the method extends.
Here’s an example of an extension method that extends the string type and capitalizes the first letter of a string:
public static class StringExtensions
{
public static string CapitalizeFirstLetter(this string input)
{
if (string.IsNullOrEmpty(input))
return input;
return char.ToUpper(input[0]) + input.Substring(1);
}
}
Once defined, the extension method can be called on any instance of the type it extends as if it were an instance method of that type:
string s = "hello world";
string capitalized = s.CapitalizeFirstLetter();
Output
"Hello world"
Here’s an example of an extension method in C#:
public static class StringExtensions…