On Sunday, May 24, 2020 6:12:31 AM MDT bauss via Digitalmars-d-learn wrote:
> Is there a way to do that?
>
> Since the following are both true:
>
> int[] a = null;
> int[] b = [];
>
> assert(a is null);
> assert(!a.length);
>
> assert(b is null);
> assert(!b.length);
>
> What I would like is to tell that b is an empty array and a is a
> null array.

There really is no difference between null and []. The compiler will use the
exact same value for both, since it makes no sense to allocate anything for
an empty array. If you want an array that's empty but non-null, then you'll
have to create a non-empty array and then slice it or set its length to 0 so
that it actually has a value for its ptr property other than null.

Regardless, == will never differentiate between a null and empty array,
because it's going to compare the lengths of the arrays and then compare the
individual elements if the lengths are the same. And with a length of 0,
there's no reason to ever check the elements, so the ptr value is
irrelevant. If you want to check whether an array is actually null, then you
need to use the is operator or check the ptr property explicitly.

And of course, the normal warnings apply that trying to differentiate
between null and empty arrays in D is almost certainly something that you
shouldn't be doing. You can do it if you're _very_ careful, but it's almost
always a terrible idea. As dumb as it arguably is, wrapping the array in a
Nullable would be _far_ less error-prone if you need to differentiate
between an array that's empty and not having a value.

- Jonathan M Davis



Reply via email to