Friday, November 16, 2007

Making Extension Methods Safer

(Note: This post refers to my previous posts about extension methods. It won't make much sense unless you read those posts first).

Last year I blogged about extension methods, explaining a risk and suggesting a solution. Now that Visual Studio 2008 is (almost) released, without any solution to the problem, I'm wondering if a solution could be added in a future release.

Yes, it could.

It would be as simple as this:

  1. Get the compiler to raise warnings when an instance method takes precedence over an extension method. (This would apply to all extension methods, whether they are in extension interfaces or not).
  2. Allow the warning to be dealt with in these ways.  Either:
    • (a) Suppress the warning using #pragma warning or the IDE's list of warnings to supress.  If you do this, you get the existing Visual Studio 2008 behaviour. OR
    • (b) Make the intent of the code explict at the call site.  If you want the extension method, call it explicitly as a static method; if you want the instance method, call it explicitly with a syntax such as the hypothetical one I proposed here.  OR
    • (c) Let the complier supress the warning for you automatically. To do so, put all the extension methods into an extension interface and make the instance implement the same interface. Then, the compiler can safely choose the instance method without issuing a warning.

For instance, in Visual Studio 2010 (or whenever it may be), Microsoft could safely put all the LINQ extension methods into extension interfaces. Users who don't care about this stuff could simply ignore or suppress the warning (option a), ending up with exactly the same behaviour they have now.

Users who do care could choose option (c), simply by implementing Microsoft's new interfaces on their own classes. That's easy, because the users already have the methods that are in the interface (that's why they are getting the warning!) so all they need to do is add the interface name to their class's list of ancestors.

The user is then left with warnings for only those rare cases of genuine ambiguity, cases where the semantics/purpose of the instance method differs from that of the extension. That's exactly when a warning is needed. These rare cases would be addressed with option (b).

In conclusion, Microsoft could safely fix the extension method problem in future version of Visual Studio.

(Update: another reason to adopt this solution)


Links to this post:

Create a Link

<< Home