Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c# - Is it "supported" to call method on nil reference in 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.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...