CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Conditional Operators
An if statement may be composed of complex expressions as well and can contain else statements to
perform more complex testing. The syntax is identical to C(++) and Java. To build complex expressions,
C# offers an expected set of conditional logical operators, as shown in Table 3-8.
Table 3-8. C# Conditional Operators
Operator
Example
Meaning in Life
&&
if(age == 30 && name == "Fred")
AND operator. Returns true if all
expressions are true.
||
if(age == 30 || name == "Fred")
OR operator. Returns true if at least one
expression is true.
!
if(!myBool)
NOT operator. Returns true if false, or
false if true.
Note The && and || operators both “short circuit” when necessary. This means that after a complex expression
has been determined to be false, the remaining subexpressions will not be checked. If you require all expressions
to be tested regardless, you can use the related & and | operators.
The switch Statement
The other simple selection construct offered by C# is the switch statement. As in other C-based
languages, the switch statement allows you to handle program flow based on a predefined set of choices.
For example, the following Main() logic prints a specific string message based on one of two possible
selections (the default case handles an invalid selection).
// Switch on a numerical value.
static void SwitchExample()
{
Console.WriteLine("1 [C#], 2 [VB]");
Console.Write("Please pick your language preference: ");
string langChoice = Console.ReadLine();
int n = int.Parse(langChoice);
switch (n)
{
case 1:
Console.WriteLine("Good choice, C# is a fine language.");
break;
case 2:
116