(non)nullable types
Denis Koroskin
2korden at gmail.com
Fri Feb 13 10:50:14 PST 2009
On Fri, 13 Feb 2009 21:43:22 +0300, Nick Sabalausky <a at a.a> wrote:
> "Christopher Wright" <dhasenan at gmail.com> wrote in message
> news:gn3os2$f6j$3 at digitalmars.com...
>> Nick Sabalausky wrote:
>>> "Brian" <digitalmars at brianguertin.com> wrote in message
>>> news:gn3dfn$2lp3$1 at digitalmars.com...
>>>> On Thu, 12 Feb 2009 08:41:54 -0500, Christopher Wright wrote:
>>>>> Brian mentioned having to check if the variable is null before using
>>>>> it.
>>>>> This would not be easy to implement, and it might be a bit hard to
>>>>> use.
>>>>> Again, I'd have to see it in use.
>>>> after a bit of thought i dont think theres much/any benefit of
>>>> forcing a
>>>> check. if nonnullable was the default then using a nullable version is
>>>> expected to be unusual and potentially unsafe.
>>>
>>> I don't see much of a point in not forcing a check. I can't think of a
>>> case where it would be useful or desirable to use a nullable type
>>> without
>>> first checking for null (except for passing it to a func that takes a
>>> nullable as a param or assigning it to another nullable of the same
>>> type,
>>> but presumably the check wouldn't be required in those cases). So it
>>> may
>>> as well be forced (when dereferencing and converting to non-nullable),
>>> since you'd never really want/need to do otherwise.
>>>
>>> Even if the compiler simplified the process by only accepting the exact
>>> pattern of "if(x !is null)...", and didn't do any fancier analysis than
>>> that, I would still consider that accptable since, as you said, it
>>> would
>>> be a non-standard use. So therefore, a (very) minor inconvenience like
>>> that would be acceptable, particularly considering it would essentially
>>> guarantee no null reference errors (aside from manual use of pointers,
>>> of
>>> course).
>>
>> The primary use case would be:
>> nullable T y = something;
>> non_nullable T x;
>> if (y) x = non_nullable_cast(y); else return;
>>
>> This is a problem if T cannot be allocated by default. I have to do
>> something like:
>> nullable T y = something;
>> if (!y) return;
>> auto x = non_nullable_cast(y);
>>
>> That isn't so bad.
>
> I still like this that someone else mentioned:
>
> T? x = something;
> if(x !is null)
> {
> // x is implicitly "T" here, not "T?"
> }
> else
> {
> // handle null condition (x is still "T?")
> }
>
>
Or use an existing syntax:
Foo? foo = ...;
if (Foo value = foo) {
// value is a local variable that is only accessible if foo is not null
} else {
// value is not accessible here
}
More information about the Digitalmars-d
mailing list