Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it "supported" to call method on nil reference in Delphi?

Tags:

c#

delphi

The following Delphi program calls method upon nil reference and runs fine.

program Project1;

{$APPTYPE CONSOLE}

type
  TX = class
    function Str: string;
  end;

function TX.Str: string;
begin
  if Self = nil then begin
    Result := 'nil'
  end else begin
    Result := 'not nil'
  end;
end;

begin
  Writeln(TX(nil).Str);
  Readln;
end.

However, in a structurally similar C# program, System.NullReferenceException will be raised, which seems to be the right thing to do.

namespace ConsoleApplication1
{
    class TX
    {
        public string Str()
        {
            if (this == null) { return "null"; }
            return "not null";    
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine(((TX)null).Str());
            System.Console.ReadLine();
        }
    }
}

Because TObject.Free uses such style, it seems to be "supported" to call method on nil reference in Delphi. Is this true ? (Let's suppose that in the if Self = nil branch, no instance field will be accessed.)

like image 785
SOUser Avatar asked Nov 18 '15 08:11

SOUser


1 Answers

It is reasonable to call a method on a nil reference, subject to the following rules:

  1. The method must not be virtual or dynamic. That is because virtual or dynamic methods are bound using the runtime type of the reference. And if the reference is nil then there is no runtime type. By way of contrast, non-virtual, non-dynamic methods are bound at compile time.
  2. You are allowed to read the value of Self, for instance to compare it against nil.
  3. In case Self is nil, then you must not refer to any instance variables.
like image 75
David Heffernan Avatar answered Oct 02 '22 20:10

David Heffernan