Sunday, February 18, 2007

Extension methods in Freya

I'm working right now on extension methods for Freya. These methods must be declared as part of static classes, with a special syntax:
public
MathTools = static class
public

method Abs: Double for Self: Double;
end
This is a (trivial) implementation for Abs:
implementation for MathTools is

method Abs: Double for Self: Double;
begin
Result := Math.Abs(Self);
end;

end;
The above declaration is translated like this:
public
MathTools = static class
publi

method Abs(Self: Double): Double;
end

implementation for MathTools is

method Abs(Self: Double): Double;
begin
Result := Math.Abs(Self);
end;

end;
There's no mistery: the bizarre "with Self" parameter has been moved to the head of the parameter list. In our example, our parameter list was initially empty, but that's an accident, not a requirement.
Let's see now how we would use the extension method:
var
d: Double;
begin
d := -1.0;
Console.WriteLine(d.Abs);
end;
It looks like the Double class had defined an Abs instance method from the first time. However, we both know that Abs was defined later, in an extension class. Of course, you can also use MathTools.Abs as a static method:
var
d: Double;
begin
d := -1.0;
Console.WriteLine(MathTools.Abs(d));
end;
This feature has a relatively long history. As far as I know, it appeared in Delphi 8, mainly as a way to add "predefined" methods to the Object base class. I didn't like the new feature. Then, it has reappeared in the C# 3.0 draft, probably as a syntatic sugar for some LINQ features. I still dislike extension methods.
There're still some loosing ends. The C# 3.0 draft suggests that extension classes are automatically registered via using clauses. I suppose there will be some kind of attribute mark at class level for telling appart extension classes from regular classes, in order to avoid full member reading in the compiler at initialization time.

Labels:

0 Comments:

Post a Comment

<< Home