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;

source
share