C# v3 Extension methods, syntactic sugar for the lack of free functions?

There’s a lot of noise coming out of the Microsoft PDC right now. Something that interested me was the future direction of C#; you can grab the spec from here.

It seems they’re adding “extension methods” which, to me, appear to be just syntactic sugar to make up for the lack of free functions…

In C++ you can have functions that aren’t part of an object. In C no functions are part of an object. These are “free” functions. You can’t have these kind of things in C# and Java because everything has to be part of an object even if the only purpose for the object’s existence is to provide a home for a collection of static methods, go figure…

In C++ a recent idiom is to prefer free functions over object methods where possible. The argument is that creating non-member, non-friend, functions increases encapsulation because these functions don’t need access to the object internals and therefore bundling them with the object simply reduces the encapsulation that the object provides by expanding the amount of code that has unnecessary access to the object’s internals.

This means that, in modern C++, you may often see things like this:

int ToInt32(const std::string &stringRep);

which can be used like this:

const int i = ToInt32(customerNumber);

Up until now the nearest that you could get to this in C# was something like this:

public class Stuff
  public static int ToInt32(string stringRep);

which can be used like this:

int i = Stuff::ToInt32(customerNumber);

The new “extension methods” proposal means that the call above can be rendered as this:

int i = customerNumber.ToInt32();

Which, in my mind, is madness. The method is not a member of the object so why should you call it using member syntax? What value does it add to be able to do this? If you’re looking to remove the crufty Stuff:: from the front of the call then why not simply allow functions to be defined at namespace scope? Then you could bring the names in with a normal using statement and use them in a way that’s expected:

int i = ToInt32(customerNumber);

It’s quite clear that ToInt32 comes from a namespace somewhere and isn’t a member of the object in question…

So, my question to all you .Net people is why is this new syntax a good thing? I can only see scope for confusion and the eventual banning of this kind of thing in local coding standards…