Class-less Extension Methods

From The Oxygene Language Wiki

Jump to:navigation, search

This is a Language topic
Feel free to add your notes to this topic below.


From Spring 2010, there is a new simplified syntax for defining extension methods.

These new methods are defined globally, in the interface section of the method instead of as part of a class. The syntax for these classes is rather simple. The method is prefixed with "extension" and the name consists of the type + the name of the extension method.

extension method IEnumerable<T>.ToAString: String;

implementation

extension method IEnumerable<T>.ToAString: String;
var
  sb: StringBuilder := new StringBuilder;
begin
  for each el in self index n do begin
    if n <> 0 then sb.Append(',');
    if assigned(el) then
      sb.Append(el.ToString());
  end;
  exit sb.ToString();
end;

Once defined, it can be used by any unit that has this namespace in the uses list like any other extension method.

More complex expressions, like arrays and sequences can be stated between parenthesis:


extension method (array of T).ToAString: String;

implementation

extension method (array of T).ToAString: String;
var
  sb: StringBuilder := new StringBuilder;
begin
  for each el in self index n do begin
    if n <> 0 then sb.Append(',');
    if assigned(el) then
      sb.Append(el.ToString());
  end;
  exit sb.ToString();
end;


BackwardCompatibility

Prior to the Spring 2010 release, an extension method had to be defined in an arbitrary class, an attribute had to be added and the actual type it extends had to be defined as the first parameter:

type
  MyExtensions = public class
   [Extension]
   class method ToAString<T>(aSelf: IEnumerable<T>): String;
  end;

implementation

class method MyExtensions.ToAString<T>(aSelf: IEnumerable<T>): String;
var
  sb: StringBuilder := new StringBuilder;
begin
  for each el in aSelf index n do begin
    if n <> 0 then sb.Append(',');
    if assigned(el) then
      sb.Append(el.ToString());
  end;
  exit sb.ToString();
end;


See Also


Oxygene-48.png

Area: Oxygene Language
Compiler version: Oxygene 5

Language GlossaryKeywordsTypesFAQHow To

Navigation
Areas
More
Toolbox