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:

Tuesday, February 13, 2007

Field-based properties

Freya already supports field-based properties. If you declare a property, but you don't provide an implementation, the compiler adds automatically a hidden field and implements the property using the new field. Even if the property is declared as read only, you can assign values to the hidden field using the property name, as long as your code is located inside the declaring class or inside another class nested in the declaring class.
I was declaring the hidden field as private, but I have realized that it's better to declare it as an internal field, so any class compiled inside the same assembly could access the field instead of the property. Of course, if the property is read only, any other class still can not write on the field. Another constraint has to do with virtual properties: if the property is declared as virtual, it's not safe to reference the field instead of the property.

Labels: , ,