2

I've recently been coding a lot in both Objective C while also working on several C# projects. In this process, I've found that I miss things in both directions.

In particular, when I code in C# I find I miss the short null check syntax of Objective C.

Why do you suppose in C# you can't check an object for null with a syntax like:

if (maybeNullObject)  // works in Objective C, but not C#   :(
{
   ...
}

I agree that if (maybeNullObject != null) is a more verbose / clear syntax, but it feels not only tedious to write it out in code all the time but overly verbose. In addition, I believe the if (maybeNullObject) syntax is generally understood (Javascript, Obj C, and I assume others) by most developers.

I throw this out as a question assuming that perhaps there is a specific reason C# disallows the if (maybeNullObject) syntax. I would think however that the compiler could easily convert an object expression such as if (maybeNullObject) automatically (or automagically) to if (maybeNullObject != null).

Great reference to this question is How an idea becomes a C# language feature?.

Edit

The short null check syntax that I am suggesting would only apply to objects. The short null check would not apply to primitives and types like bool?.

5
  • this more as a witty comment than an answer: in certain situations you can get around the check for null often times by using the Null Object Pattern. Commented Feb 24, 2012 at 23:08
  • @Sam The bigger (billion dollar mistake) question is: why are there null values in either language? :-) That is one thing that C# could have fixed, but didn't :( And yes, this question has been asked (and likely closed) at least a few times on SO. Commented Feb 24, 2012 at 23:11
  • 2
    I would prefer the stricter syntax for the simple fact of nullable bool values, guess you haven't come across those recently. Its not very hard to write != null Commented Feb 24, 2012 at 23:16
  • Have you ever mistakenly written if (foo = bar) instead of if (foo == bar)? Because if works only on bools in C#, the former doesn't compile (with the exception of when foo is bool). Commented Feb 24, 2012 at 23:58
  • @svick Thankfully, modern C compilers have these little things called "warnings" :) Commented Feb 25, 2012 at 2:14

4 Answers 4

9

Because if statements in C# are strict. They take only boolean values, nothing else, and there are no subsequent levels of "truthiness" (i.e., 0, null, whatever. They are their own animal and no implicit conversion exists for them).

The compiler could "easily convert" almost any expression to a boolean, but that can cause subtle problems (believe me...) and a conscious decision was made to disallow these implicit conversions.

IMO this was a good choice. You are essentially asking for a one-off implicit conversion where the compiler assumes that, if the expression does not return a boolean result, then the programmer must have wanted to perform a null check. Aside from being a very narrow feature, it is purely syntactic sugar and provides little to no appreciable benefit. As Eric Lippert woudl say, every feature has a cost...

You are asking for a feature which adds needless complexity to the language (yes, it is complex because a type may define an implicit conversion to bool. If that is the case, which check is performed?) only to allow you to not type != null once in a while.

EDIT:

Example of how to define an implicit conversion to bool for @Sam (too long for comments).

class Foo
{
    public int SomeVar;
    public Foo( int i )
    {
        SomeVar = i;
    }

    public static implicit operator bool( Foo f )
    {
        return f.SomeVar != 0;
    }
}

static void Main()
{
    var f = new Foo(1);         
    if( f )
    {
        Console.Write( "It worked!" );
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

While I agree it is a "good choice" (one that I prefer in a statically typed language), it is not the "only [correct] choice". It all comes down to how a language defines it's "falsey values"; C (and Objective-C) have no proper "false", just a 0 (or nil on Objective-C) and non-0 notion ;-)
Agreed. I'm not sure an extra 8 characters (including spaces) qualifies as overly verbose, but I do appreciate the clarity those characters bring when scanning code.
@pst: As is the case with most design choices. There are almost always multiple choices, but one has to be made.
@pst Yes, and that decision in C is why its so easy to shoot yourself in the foot. I'd argue the C decision was a bad one.
@EdS. Can you give an example of how a type can define an implicit conversion to bool? Does this mean an expression like if (myObj) is possible (not for null checking) if the class definition for myObj has an implicit conversion to bool? If there is some implicit conversion to bool, I'd be compelled to agree with you that throwing in the null check would be VERY confusing. Also, I agree that being more explicit makes the code intent more clear and this feature request is certainly syntactic sugar. I just miss it. :) That's OK though, .NET is really awesome.
|
4

One potential collision is with a reference object that defines an implicit conversion to bool.

There is no delineation for the compiler between if(myObject) checking for null or checking for true.

Comments

1

The intent its to leave no ambiguity. You may find it tedious but that short hand is responsible for a number of bugs over the years. C# rightly has a type for booleans and out was a conscience decision not to make 0 mean false and any other value true.

Comments

1

You could write an extension method against System.Object, perhaps called IsNull()?

Of course, that's still an extra 8 or 9 characters on top of the code you'd have to write for the extension class. I think most people are happy with the clarity that an explicit null test brings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.