Self in class methods

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Class > class methods > Self in class methods

In Delphi, Self inside a class method represents the class on which the class method is invoked. This is different from C# static methods, where no this or Self value exists.

 

For non-virtual Delphi class methods, Delphi2C# usually translates the method to a normal C# static method of the declaring class. In this case, unqualified constructor calls such as Create are translated as construction of the declaring class.

 

Example Delphi code:

 

class function TBase.ClassMethod(X: Integer): Integer;

begin

  with Create do

  begin

    Init;

    Done;

    Free;

  end;

 

  Result := X;

end;

 

Generated C# code:

 

public static int ClassMethod(int X)

{

    TBase with0;

 

    with0 = new TBase();

 

    try

    {

        with0.Init();

        with0.Done();

    }

    finally

    {

        TObject.Free(with0);

    }

 

    return X;

}

 

For virtual class methods, Delphi2C# generates static C# methods for the individual classes and uses TClass to dispatch the call to the correct class implementation.

 

Example Delphi call:

 

P.ClassVirtual(1);

 

Possible generated C# code:

 

P.ClassType().InvokeClassMethod<int>("ClassVirtual", 1);

 

Example class call:

 

TDerived.ClassVirtual(1);

 

Possible generated C# code:

 

TClass.Of<TDerived>().InvokeClassMethod<int>("ClassVirtual", 1);

 

This means that the virtual class-method dispatch is handled by TClass. The generated static method body itself does not receive an explicit hidden Self parameter.

 

This approach covers the common case where each overriding class method has its own generated C# method body. However, it is not a full emulation of Delphi's class-method Self in all possible cases. In particular, if a virtual class method is inherited without being overridden and its inherited implementation depends on Self to create an instance of the actual calling class, additional runtime support would be required.

 

For example, a complete emulation could pass the current TClass value as an additional hidden parameter to the generated method. Delphi2C# currently uses the simpler TClass dispatch model instead.



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content