Why does not a NullReferenceException occur?

I showed this to several colleagues, and no one received an explanation. I came across this by pure chance, as I thought I found an error in our code, but was surprised to see that the code really works. Here is a simplified version. This was done using XE-2.

Everyone I've talked to so far also expects to throw a NullReferenceException.

 TUnexplainable = class(TObject)
  public
    function Returns19: Integer;
  end;

function TUnexplainable.Returns19: Integer;
begin
  Result := 19;
end;

The following test NEVER works, but it succeeds. Why is a NullReferenceException not thrown?

procedure TTestCNCStep.ShouldNeverEverWorkV4;
var
  Impossible: TUnexplainable;
  Int1: Integer;
begin
  Impossible := nil;
  Int1 := Impossible.Returns19; // A Null Reference Exception should ocurr here!!! Instead the method Returns19 is actually invoked!!!!
  Check(Int1 = 19);
end;

Test resuts

+4
source share
2 answers

Self. , , :

//function TUnexplainable.Returns19: Integer;
function TUnexplainable_Returns19(Self: TUnexplainable): Integer;
begin
  Result := 19;
end;

//procedure TTestCNCStep.ShouldNeverEverWorkV4;
procedure TTestCNCStep_ShouldNeverEverWorkV4(Self: TTestCNCStep);
var
  Impossible: TUnexplainable;
  Int1: Integer;
begin
  Impossible := nil;
  Int1 := TUnexplainable_Returns19(Impossible);
  Check(Int1 = 19);
end;

, Returns19() Self -, nil.

, - Self, :

type
  TUnexplainable = class(TObject)
  public
    Number: Integer;
    function ReturnsNumber: Integer;
  end;

function TUnexplainable.ReturnsNumber: Integer;
begin
  Result := Number;
end;

procedure TTestCNCStep.ShouldNeverEverWorkV4;
var
  Impossible: TUnexplainable;
  Int1: Integer;
begin
  Impossible := nil;
  Int1 := Impossible.ReturnsNumber; // An EAccessViolation exception will now occur here!!!
end;

, .

( , ), , Self, nil . - .

+10

Self, .

#, Delphi Self (this #).

+5

All Articles