Does null ever equal anything?

Yesterday’s discussion of nulls got me to thinking about this common bit of syntax in C#:

if (myObject == null)
{
...

But here’s the thing: null is not data. It’s metadata. That is, it describes the state of a variable, not its contents.

Null indicates the absence of a value. So the above code says, is myObject’s value equal to not having a value? Seems strange.

Other languages seem to make this distinction. VB (if I recall) has the construct “Is Nothing”. SQL uses “IS NULL” (as opposed to “= NULL”). These syntaxes make more sense to me — they differentiate testing a value and testing the existence of a value.

I imagine the “== null” operator is allowed in C# as a syntactic convenience. I mean, it’s readable and easy to remember. No complaints.

But I bet this requires the compiler to extract those statements and send them to a different evaluation algorithm. It’s a different kind of test. Curious if any C# language designers would have an insight.

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Does null ever equal anything?

  1. Eric Lippert says:

    In VB, it’s "IsNull(whatever)" — there’s a distinction in VB between "Nothing" (the null object), "Empty" (the uninitialized variant) and "Null" (database null).

    Your point is well taken, and this was a big debate on the C# design team. If you read the spec you’ll see that "== null" and "!= null" are special-cased in the compiler to specifically mean "check to see whether the instance of nullable value type on the left-hand side is null". This is in contrast to VB, which has three-valued equality — comparing anything to null in VB results in null.

    Both approaches make some sense. In C# we’re being inconsistent with null lifting for literals, but the code reads naturally. In VB, they’re being fully consistent, but makes it easy to accidentally write a comparison which is never true.

  2. Stacy Bank says:

    The very root of your writing whilst appearing reasonable in the beginning, did not settle well with me personally after some time. Somewhere throughout the sentences you were able to make me a believer unfortunately just for a while. I still have got a problem with your leaps in logic and you would do nicely to help fill in those breaks. In the event you actually can accomplish that, I will certainly end up being impressed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s