Chapter 2: Learning Just Enough C# or VB.NET: Basic Syntax

57

The accountType enum variable is a BankAccount and is initialized to have the value of the Checking member of BankAccount. The next statement uses a ternary operator to check the value of accountType, evaluating whether it is Checking. If so, message is assigned with the first string. Otherwise, message is assigned with the second string. Of course, we know it’s the first string because the example is so simple that you can see it is coded that way.

Branching Statements

A branching statement allows you to take one path of many, depending on a condition. For example, consider the case for giving a customer a discount based on whether that customer is a preferred customer. The condition is whether the customer is preferred or not, and the paths are to give a discount or charge the entire price. Two primary types of branching statements are if and switch (Select Case in VB). The following sections show you how to branch your logic using if and switch statements.

Expressions

If statements allow you to perform an action only if the specified condition evaluates to true at runtime. Here’s an example that prints a statement to the console if the contents of variable result is greater than 48 using the > (greater than) operator:

C#:

if (result > 48)

{

Console.WriteLine("result is > 48");

}

VB:

If result > 48 Then

Console.WriteLine("Result is > 48")

End If

C# curly braces are optional if you only have one statement to run after the if when the condition evaluates to true, but the curly braces are required when you want two or more statements to run (also known as “to execute”) should the condition be true. The condition must evaluate to either a Boolean true or false. Additionally, you can have an else clause that executes when the if condition is false. A clause is just another way to say that an item is a part of another statement. The else keyword isn’t used as a statement

Page 80
Image 80
Microsoft 9GD00001 manual Branching Statements, Expressions