9.1. The if Statement

The if statement is a control statement that executes a block of code if an expression evaluates to true. It takes this form:

if (expression)
  statement1
else
  statement2

where

  • expression is an expression that can be implicitly converted to bool or a type that contains overloading of the true and false operators

  • statement1 is the embedded statement(s) to be executed if expression is true

  • statement2 is the embedded statement(s) to be executed if expression is false

Note that unlike C++, C# and Java do not allow the expression to be evaluated to 1 or 0. That is, the integer 1 does not stand for true, and 0 does not stand for false.

If expression is true, then statement1 is executed. If the optional else clause exists and expression ...

Get .NET for Java Developers: Migrating to C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.