O'Reilly logo

Microsoft® Visual C#® 2008 Step by Step by John Sharp

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using if Statements to Make Decisions

When you want to choose between executing two different blocks of code depending on the result of a Boolean expression, you can use an if statement.

Understanding if Statement Syntax

The syntax of an if statement is as follows (if and else are C# keywords):

if ( booleanExpression )
    statement-1;
else
    statement-2;

If booleanExpression evaluates to true, statement-1 runs; otherwise, statement-2 runs. The else keyword and the subsequent statement-2 are optional. If there is no else clause and the booleanExpression is false, execution continues with whatever code follows the if statement.

For example, here's an if statement that increments a variable representing the second hand of a stopwatch (minutes are ignored for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required