Null references redux

Max Samukha spambox at d-coding.com
Wed Sep 30 08:26:20 PDT 2009


On Wed, 30 Sep 2009 08:53:57 -0400, bearophile
<bearophileHUGS at lycos.com> wrote:

>If nonnull class references are added to D, then it can be good to add nonnull struct pointers too, to avoid similar bugs.
>
>(In C# for a struct you define a "default" one, that gets used by the compiler as the default one when the struct reference is null).
>
>Bye,
>bearophile

Don't get confused by 'new' in struct initializers. Structs in C# are
value types. You can box them, use pointers to them in 'unsafe'
context but you can't directly allocate them on heap. So there is no
nullable references to structs. When you do:

struct S
{
  public int x;
}

S s = new S(); // x is default initialized to 0

the struct is still allocated on stack and passed by value.

S s;
s.x = 1; //error, struct is not initialized

BTW, C# does have null-initialization problems regardless of flow
control. One example:

struct S
{
   public Object obj;
}

S s = new S();
s.obj.ToString(); // null-reference exception;



More information about the Digitalmars-d mailing list