Delphi self keyword

Yes, Delphi's Self is the direct analogue of Java's this.


Self is very similar to this in Java, C++, or C#. However it is a little bit more invoked, as the following code will show.

In Delphi, you can have class methods that are not static but also have a Self pointer, which then obviously does not point to an instance of the class but to the class type itself that the method is called on.

See the output of this program:

program WhatIsSelf;

{$APPTYPE CONSOLE}

type
  TAnimal = class
    procedure InstanceMethod;
    class procedure ClassMethod;
    class procedure StaticClassMethod; static;
  end;

  TDog = class(TAnimal)
  end;

class procedure TAnimal.ClassMethod;
begin
  Writeln(Self.ClassName);
end;

procedure TAnimal.InstanceMethod;
begin
  Writeln(Self.ClassName);
end;

class procedure TAnimal.StaticClassMethod;
begin
//  Writeln(Self.ClassName); // would not compile with error: E2003 Undeclared identifier: 'Self'
end;

var
  t: TAnimal;
begin
  t := TDog.Create;
  t.InstanceMethod;
  t.ClassMethod;

  TAnimal.ClassMethod;
  TDog.ClassMethod;

  Readln;
end.

Tags:

Delphi

Self