I am learning Delphi reading Marco Cantu\'s book and it\'s super complete. It\'s very clear but I have a doubt about the keyword self
. I already have experience
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.
Yes, Delphi's Self
is the direct analogue of Java's this
.
Formally speaking, Self
is a normal identifier (that is automatically predeclared in some circumstances).
Self
is automatically defined in the implementation of methods and class methods and its purpose there is similar to this
in Java as already mentioned. The underlying technology is analogous to the Result
variable in ordinary functions.
In other words, there is no self keyword (that's why it's typically written with an uppercase S
). Whenever you want (and can [*]), you may introduce your own Self
variable, method or class.
type
// TForm1 ommitted
Self = class
function Self: Integer;
end;
function Self.Self: Integer;
begin
Result := SizeOf(Self);
end;
You'll have of course difficulties to instantiate an object of this type within a method, in these cases, you have to use it through an adapter function (or procedure):
function UseSelf: Integer;
var
S: Self;
begin
S := Self.Create;
Result := S.Self;
S.Free;
end;
function VarSelf: Integer;
var
Self: Integer;
begin
Self := SizeOf(Result);
Result := Self;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(UseSelf)+' '+IntToStr(VarSelf));
end;
[*] You cannot declare a Self
variable within methods, because there is already such a declaration and that's exactly what the error says:
Identifier redeclared: 'Self'
self is a special variable that points to the object that owns the currently executing code and it gives access to the current object. In Ruby programming language there is self too, however equivalent of it in JavaScript, C++, C# and Java is this and in VB is Me.