Back to C# Language Enhancements.Extension methods allow the introduction of methods to any type without changing that type. They allow the developer to add a method to a type for any reason. Instance members have priority if they are the same name with the same argument list.
In the words of the C# 3.0 Specification:
Extension methods are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods.
A simple example (pay attention to the "this" operator in the argument definition):
public static string Encrypt(this string input)
{
// TODO: encrypt string and return string
}
would allow you to use the Encrypt method an ANY string instance using the following code:
string s = "Test";
string encrypted = s.Encrypt();
Granted, on this simple case, a simple static library might have been useful. However, if you were added the 50 different standard query operators that make up the LINQ to Objects
Standard Query Operators with overloads for different types you might consider extension methods key.
There is one warning that the C# 3.0 specification makes clear:
Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.
Extension members of other kinds, such as properties, events, and operators, are being considered but are currently not supported.
Extension methods are made available to code by being "in-scope" through the use of the using clause. An example is that the Standard Query Operators that Microsoft shipped as part of LINQ in C#3.0 (Visual Studio 2008) are made available to user code by adding the following using clause at the top of a class library (or any code):
using System.Linq;
Visual Studio immediately makes any extension method in-scope when viewing the intellisense on any member. E.g. if you look at a string, you will see extension methods for a string in ADDITION to any instance methods. If an instance variable was an IEnumerable, you would have access to any extension methods that extended that interface (all of the LINQ to Objects standard Query Operators).
There has been some discussion about the dangers of versioning and behaviour changes due to somebody implementing an instance method of the same name. See
John Rusk's blog, and
Bart De Smet's Blogfor details.
EditReferences
Google search: Extension Methods C#