Starting in .NET 3.5 is a feature called extension methods. Extension methods allow developers to extend classes with their own instance methods. This is a concept often called mix-ins in other languages.
Take for example the following piece of code.
In the above, trivial, example we see a helper class that has a static method to determine if a string is “short”. While the example is ridiculous, it is helpful in illustrating the root desire for extension methods. Often times our source code is littered with helper class very similar to the above one.
Also littered around your code is undoubtedly usages of such utility classes. So, for example, you would have usages such as:
Extension methods in .NET 3.5 provide a syntactic short cut for the above. To change our IsShort function to be an extension of System.String prefix the this keyword to the parameter list.
That is all that is needed to turn an ordinary helper method into an extension method in .NET 3.5. There are, however, a few rules to keep in mind with extension method.
- Only static methods of static classes can be extension methods.
- The this keyword can only be applied to the first parameter.
- Extension methods are only visible when their containing namespace is imported via C#’s “using” statement.
With those simple rules you start converting your static helpers into extensions on the classes that they service, allow for easier customization of the core .NET libraries (or other 3rd party libraries).