O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

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

Conditional Branching Statements

Although methods branch unconditionally, often you will want to branch within a method depending on a condition that you evaluate while the program is running. This is known as conditional branching. Conditional branching statements allow you to write logic such as, “If you are over 25 years old, then you may rent a car.”

C# provides a number of constructs that allow you to write conditional branches into your programs; these constructs are described in the following sections.

if Statements

The simplest branching statement is if. An if statement says, “if a particular condition is true, then execute the statement; otherwise, skip it.” The condition is a Boolean expression. An expression is a statement that evaluates to a value, and a Boolean expression evaluates to either true or false.

The formal description of an if statement is:

if (expression)Statement1

This is the kind of description of the if statement you are likely to find in your compiler documentation. It shows you that the if statement takes an expression (a statement that returns a value) in parentheses, and executes Statement1 if the expression evaluates true. Note that Statement1 can actually be a block of statements within braces, as illustrated in Example 5-2.

Example 5-2. The if statement

using System; namespace Branching { class Test { static void Main( ) { int valueOne = 10; int valueTwo = 20; int valueThree = 30; Console.WriteLine( "Testing valueOne against valueTwo..." ); if ( valueOne ...

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