Extension Methods

Summary

Extension Methods extend existing .NET types with new methods. Extension methods make it possible to extend existing types and constructed types with additional methods, outside their definitions.

Extension methods allow developers to add new methods to an existing type without having to create an inherited class or to recompile the original.

An Extension Method has two stipulations:

  • It is declared as static in an outer-level static, nongeneric class.
  • The type it is extending is declared as the first parameter, preceded by the keyword "this".

Code Example

This code sample extends the String base class by adding a SpaceToUnderscore() method.

public static class MyExtensions { public static string SpaceToUnderscore(this string source) { char[] cArray = source.ToCharArray(); string result = null; foreach (char c in cArray) { if (Char.IsWhiteSpace(c)) result += "_"; else result += c; } return result; } } class Program { static void Main(string[] args) { String test = "This is a test."; Console.WriteLine(test.SpaceToUnderscore()); Console.Read(); } }

Insert the keyword "this" before the first method parameter, which indicates to the compiler the type you want to extend. The method and its class must be static.