This syntax regarding null checking baffles me

Steven Schveighoffer schveiguy at gmail.com
Thu Jan 7 17:24:30 UTC 2021


On 1/7/21 9:13 AM, 12345swordy wrote:
> On Thursday, 7 January 2021 at 05:14:44 UTC, Basile B. wrote:
>> On Thursday, 7 January 2021 at 04:57:55 UTC, 12345swordy wrote:
>>> if (c !is null) Why?????
>>>
>>> Would it be simpler to type
>>>
>>> if (c is not null)
>>>
>>> on a related note. Why are not we allowed to do this?
>>>
>>> if (c != null)
>>
>> it is allowed
>>
> "For class objects, the == and != operators are intended to compare the 
> contents of the objects, however an appropriate opEquals override must 
> be defined for this to work. The default opEquals provided by the root 
> Object class is equivalent to the is operator. Comparing against null is 
> invalid, as null has no contents. Use the is and !is operators instead."
> 
> Not allowed for classes apparently.

Historically (before this restriction was added), when you compared 2 
class objects, the code:

obj != expr

translated directly to:

!obj.opEquals(expr)

Which, if obj was null, resulted in a segmentation fault.

Thus the case of:

obj != null

is both error prone and ironic:

if(obj != null) { /* use obj */ }

This crashes if obj actually is null. Therefore, the syntax `obj !is 
null` is required.

You could find somewhere on these forums where I advocated for this, and 
Walter finally agreed.

Since then, the code for equality now translates to:

object.opEquals(obj1, obj2)

which will not crash, even if the object that isn't null improperly 
handles a comparison with null.

However, it's still more "correct" to say `is null` or `!is null`, as 
technically there's no other comparison that makes sense. So we *could* 
relax the restriction, but I think the existing expression is clearer.

-Steve


More information about the Digitalmars-d mailing list