#169 – The if Statement Must Always Include a Boolean Expression

In C++, an if statement can use a conditional expression that resolves to a numeric value.  The statement following the if statement will execute when this expression resolves to any non-zero value.  This form of the if statement is not allowed in C#.

            uint leaves = CountLeavesInBackyard();

            // Works in C++, but is not allowed in C#
            if (leaves)
            {
                RakeLikeHeck();
            }

Since the if statement must use a boolean expression in C#, we’d rewrite the code as:

            if (leaves > 0)
            {
                RakeLikeHeck();
            }

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment