Extension methods in C# enable you to extend existing types without having to create a new type. This essentially means that you can take the class String and add methods to it that extends it, and when you create a string those methods become available. You just have to make sure you include the namespace of the class that implements the methods. A very basic example would be to create an extension method that returns the length of a string. So you start off first by creating:
namespace MyExtensionMethods
{
public static class MyExtensionMethods
{
public static int ReturnText(this String text)
{
return text.Length;
}
}
}
Notice the this keyword before String. Also notice that the class is static and that the method is static, which means that the class can only contain static methods. If you create an instance method in a static class you will get a compiler error. To use the extension method you include the using directive:
namespace ExtensionMethods2
{
using MyExtensionMethods;
class Program
{
static void Main(string[] args)
{
string s = "Test";
Console.WriteLine(s.ReturnText());
}
}
}
Notice that the string s now has an extra method associated to it called ReturnText.