Re: Some notes on C# 3.0 (was RE: [DOTNET-CX] How to overload == for System.Double)

Fabian Schmied <[email protected]> Sun, 4 Feb 2007 19:57:22 +0100
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <[email protected]>
> For the most part, I agree.  My comments were mostly about extension
> methods; which aren't "sugar".
[...]
> There's nothing in 2.0
> that allows you to do what extension methods allow you to do in 3.0.

Hm, as I see it, extension methods actually are syntactic sugar, much
more so than lambda expressions are, for example. (After all, lambda
expressions enable expression trees to be generated.)

An extension method is an ordinary static method (of a class), for
which the compiler allows you to specify the first argument before the
method name instead of after it at the call site. Where exactly do you
see the relationship with C++ nonmember functions?

For illustration, with the following class declaration (syntax from memory):

public static class ExtensionMethods {
  public static void Print<T>(this IEnumerable<T> collection) {
    foreach (T t in collection) {
      Console.WriteLine(t);
    }
  }
}

You can either call Print traditionally:

string[] items = new string[] {"one", "two", "three"};
ExtensionMethods.Print(items);

Or in this new way:
string[] items = new string[] {"one", "two", "three"};
items.Print();

Since the latter is just a "shortcut" for the former achieved with an
additional compiler lookup step, this for me is syntactic sugar. (Nice
one, actually, I've been wishing for that for a long time. The only
thing that I think might require some rethinking is how extension
methods get imported into the current scope.)

Fabian

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com