Why does nobody seem to think that `null` is a serious problem in D?

Alex sascha.orlov at gmail.com
Wed Nov 21 17:46:29 UTC 2018


On Wednesday, 21 November 2018 at 17:09:54 UTC, Neia Neutuladh 
wrote:
> On Wed, 21 Nov 2018 17:00:29 +0000, Alex wrote:
>> C# wouldn't reject the case above, would it?
>
> C# *would* reject that (you can't call any methods on a null 
> object), but in D, it compiles and runs and doesn't segfault.

No, it wouldn't. And it doesn't.

´´´ C# ´´´
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApp1
{
     sealed class C
     {
         public int dummy;
         public void baz()
         {
             if (this is null)
             {
                 Debug.WriteLine(42);
             }
             else
             {
                 Debug.WriteLine(dummy);
             }
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             C c;
             Random random = new Random(4);
             int randomNumber = random.Next(0, 100);
             if (randomNumber < 50)
             {
                 c = new C
                 {
                     dummy = 73
                 };
             }
             else
             {
                 c = null;
             }
             c.baz();
         }
     }
}
´´´
compiled against 4.6.1 Framework.

However, of course, there is a NullReferenceException, if c 
happens to be null, when calling baz.

So the difference is not the compiler behavior, but just the 
runtime behavior...

How could the compiler know the state of Random anyway, before 
the program run.


More information about the Digitalmars-d-learn mailing list