IntelliSense is great for discovering what methods are available on an object. Frustration can arise when you wish to extend existing types that you do not control.
C# 3 solves this problem by allowing you to write methods that appear as if they are part of the type. In reality they are static methods declared on a static type with the special this keyword in front of the first parameter which indicates the type - or interface - they appear on.
Code
csharp
Console.WriteLine(customer.GetSalutation());
// ...
static class CustomerHelper
{
public static string GetSalutation(this Customer c)
{
return "Dear " + c.Title + " " + c.Surname;
}
}csharp
Console.WriteLine(CustomerHelper.GetSalutation(customer));
// ...
static class CustomerHelper
{
public static string GetSalutation(Customer c)
{
return "Dear " + c.Title + " " + c.Surname;
}
}Notes
- Extension methods can only access members that are accessible to the static class (public members, or internal ones within the same assembly) - never private or protected members
- Extension methods must be static methods of a non-nested, non-generic static class
- Extension methods can also be used to "add" methods to interfaces!
- Reserve extensions for common operations - do not pollute IntelliSense with every helper you can think of
- Extension members C# 14.0 add extension properties and static extension members
The first parameter must be prefixed with this but it does not have to be a class or struct. You can also extend interface, enums, and generic types.
enums with methods are very convenient and feel more like their rich Java cousins- To extend an open generic type such as
List<T>the method must itself be generic. Remember to place generic type constraints on the method to ensure it only appears for types it actually deals with.