Nullable!T with T of class type

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jun 26 21:54:49 UTC 2018


On Tuesday, June 26, 2018 19:03:20 kdevel via Digitalmars-d-learn wrote:
> On Monday, 25 June 2018 at 22:58:41 UTC, Jonathan M Davis wrote:
> > On Monday, June 25, 2018 19:40:30 kdevel via
> >
> > Digitalmars-d-learn wrote:
> >>     R r;
> >>
> >>     if (r.s is null)
> >>
> >>        throw new Exception ("some error message");
>
> [...]
>
> >> Why can't this programming error be detected at compile time?
> >
> > If you have a function that accepts Nullable!T, when that
> > function is called, how on earth is it going to know whether
> > the argument it received was null at compile time?
>
> That was not the error. The error was that I used is null instead
> of .isNull() which lead to a different Exception (Error).

Well, get checks whether the Nullable isNull, and throws an Error if it is,
which is what you showed in your original post. If you want a Nullable to
have the value of null, then you have to explicitly set it to null. Nullable
really doesn't have anything to do with the null value for pointers or
references beyond the fact that it allows a way to emulate that behavior for
non-nullable types by using a bool.

isNull returns whether the Nullable has been given a value or not, whereas
checking the value with is null means checking whether it has a value and
whether that value is null. If that behavior is not what you want, then you
will have to find a different solution, though honestly, I don't understand
why folks keep trying to put nullable types in Nullable in non-generic code.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list