Extension Methods are powerful and dangerous by ThinqLinq

Extension Methods are powerful and dangerous

Much of the querying functionality present in LINQ and the associated techologies leverage a new language feature known as Extension methods. With an extension method you can "extend" any type simply by adding the "this" keyword before the first parameter of the method definition. The LINQ samples primiarly extend IEnumerable<T>. However Extension methods can be used to extend any type.

Perhaps the following sample class can help explain the Extension method. In this example, I will simply extend the string data type with a new method that capitolizes the first letter of each word. I begin with a normal static method on a static class.

public static class MyExtension
{
public static string TitleCase(string source)
{
return new System.Globalization.CultureInfo("en-US").TextInfo.ToTitleCase(source);
}
}

The standard implementation would be as follows:

string test = "this is a test"
Console.WriteLine(MyExtension.TitleCase(test));

So far there is nothing new. To change the TitleCase method into an extension method, all we need to do is add "this" prior to the first parameter as follows:

public static string TitleCase(this string source)

As long as the MyExtension class is in scope, usage of the new extension method is as simple as the following:

string test = "this is a test"
Console.WriteLine(test.TitleCase());

In fact, you can shorten it to the following:

string test = "this is a test".TitleCase();

Here I have extended the String type with a method that it would not otherwise have. A word of warning is important here. Use Extension methods only after all other options have been exhausted. There are a number of reasons why an extension method is dangerous, including potential namespace collisions and increased difficulty maintaining code when a method is not directly present on a class. Extension methods can be powerful, but dangerous if mis-used.

Posted on - Comment
Categories: C# -
comments powered by Disqus