Extension methods are special methods which can simulate the addition of new instance members to an already existing class.
Of course, this "extension" is only apparent. Actually, an extension method is a static method declared in another class, and the "extension" illusion is achieved through simple syntactic transformations.
Extension methods can only be declared inside a static class, and they must be declared using this syntax:
method method-name parameters optional-return
for identifier: type-reference;
We could design, for instance, a static class with methods that will extend the capabilities of the predefined System.Int32 class:
IntTools = static class
public
method Sqrt: Integer for Self: Integer;
implementation
method Sqrt: Integer for Self: Integer;
begin
Result := Integer(Math.Sqrt(Self));
end;
end;
I have used Self for the extension parameter name, but you can use any other valid identifier. The above declaration is almost equivalent to this one:
IntTools = static class
public
method Sqrt(Self: Integer): Integer;
implementation
method Sqrt(Self: Integer): Integer;
begin
Result := Integer(Math.Sqrt(Self));
end;
end;
You could even use Sqrt as if it were declared that way:
var i: Integer := 400; Console.WriteLine(IntTools.Sqrt(i));
However, you would prefer this variant:
var i: Integer := 400; Console.WriteLine(i.Sqrt);
Now, the name of the class containing the method has been dropped, and it looks as if Sqrt were originally declared as part of the System.Int32 class.
The Freya Programming Language
Methods
Generic methods
Type declarations
Type members
Constructors
User defined operators
Iterators
Fields
Properties
Indexers
Events