Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...