Monday, 31 March 2008

Extension methods

C# 3.0 has introduced a new language feature called extensions methods. What extensions methods let you do is add new methods to any type without deriving from that type or modifying the source of that type. For example you can add a new method "StartsWithNum" to the type "String".


namespace ConsoleApplication1
{
public static class Foo
{
public static bool StartsWithNum(this string s)
{
for (int i = 0; i < 9; i++)
{
if (s.StartsWith(i.ToString()))
return true;
}
return false;
}
}
class Program
{
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(s.StartsWithNum());
}
}
}


Scott Gu's blog has a good post explaining extension methods.

In my opinion they are a bad idea because of the following reasons:
  1. Extension methods encourage that you to patch up your original code from files elsewhere.
  2. The programmer's "is-a", "has-a" dilemma gets an addition and gives us a trilemma: subclass, wrap or extend?
  3. Anyone not using Visual Studio 2008 is going to have a tough time navigating through the code as extension methods can be defined in any namespace.
  4. Programmers may start assuming that the extension method is part of the framework, when it may not be.

1 comments:

Anonymous said...

hmm..i am pretty sure it would be used in the wrong manner..just like the mutable keyword in C++ :D