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 appears 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
C#
public void PrintSalutation(Customer customer)
{
Console.WriteLine(customer.GetSalutation());
}
static class CustomerHelper
{
public static string GetSalutation(this Customer c)
{
return "Dear " + c.Title + " " + c.Surname;
}
}
C#
public void PrintSalutation(Customer customer)
{
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 public properties and methods of the object
- Extension methods must be static methods of a 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
The first parameter must be prefixed with this
but it does not have to be a class
or struct
. You can also extend interface
, enum
s, and generic types.
enum
s with methods are very convenient and feel more like their rich Java cousins- Generic types require the method be generic. Remember to place generic type constraints on the method to ensure it only appears for types it actually deals with.