Extension Method is a special kind of static method that allows you to "extend" an existing class or interface with new methods without modifying the original type’s code and without creating a derived type.
- Must be declared in a static class.
- Must be a static method.
- The first parameter specifies the type being extended and is preceded by the
this
keyword. - Can be called as if it were a method of the extended type.
public static class ExtensionClass
{
public static ReturnType MethodName(this Type parameter, OtherParameters)
{
// Method implementation
}
}
-
To add helper methods to existing classes .
-
Want more readable code.
-
To reduce code duplication.
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
In this example, we define an extension method IsNullOrEmpty
for the string
class, allowing us to call it as if it were a method of the string
class itself.
How to use:
string myString = null;
bool result = myString.IsNullOrEmpty();
Console.WriteLine(result);
Output:
True
using System;
public static class StringExtensions
{
// Extension Method
public static bool IsCapitalized(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
return char.IsUpper(str[0]);
}
}
class Program
{
static void Main()
{
string name = "Code";
string word = "codeline";
Console.WriteLine(name.IsCapitalized()); // True
Console.WriteLine(word.IsCapitalized()); // False
}
}