Class helpers

Top  Previous  Next

New features since Delphi 7 > Class helpers

 

 

A quite similar feature to Delphi's helper records and helper classes are the extension methods of C#.Therefore these helper are converted to classes containing the according extension methods. Taking the example from:

 

http://delphi.about.com/od/oopindelphi/a/understanding-delphi-class-and-record-helpers.htm

 

 

TStringsHelper = class Helper for TBase

private 

  function GetTheObject(const AString: String): TObject; 

  procedure SetTheObject(const AString: String; const Value: TObject); 

public 

  property ObjectFor[const AString : String]: TObject Read GetTheObject Write SetTheObject; 

end;

 

becomes with Delphi2C#  to

 

public static class TStringsHelper

{

  public static TObject GetTheObject(this TStrings helped, string aString)

  {

    ...

  }

  public static void SetTheObject(this TStrings helped, string aString, TObject Value)

  {

    ...

  }

  /*property ObjectFor [aString: string]: TObject read GetTheObject write SetTheObject;*/

  public static TObject ReadPropertyObjectFor(this  helped, string aString) { return GetTheObject(helped, aString);}

  public static void WritePropertyObjectFor(this  helped, string aString, TObject Value){SetTheObject(helped, aString, Value);}

};

 

Regardless whether a helper class is defined in the interface part of a Delphi source file or in the implementation part, the generated C# class is put in front of the C# file outside of the class that is constructed for global parts of the unit, because extension methods must be defined in a top level static class.

 

 

If fields of the helped type shall be changed by an extension method, the "this" parameter has to be passed by reference.

 

 

 

Remark

 

Till the Delphi compiler 10 Seattle it was allowed to access private members of the helped class via its class helper regardless in which unit the helped class was declared. With the just described C# pendant this is not possible. However, this possibility broke OOP encapsulation rules and was regarded as a bug, which was fixed with Delphi compiler 10.1 Berlin. You can read more about this bug fix here:

 

 

http://blog.marcocantu.com/blog/2016-june-closing-class-helpers-loophole.html

 

 

 



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content