Every modern programming language supports the notion of branching and conditional logic. This gives your applications the ability to do different things based on current input, events, error conditions, or any condition that can be
expressed
logically. This section first shows you how C# allows you to form logical expressions and how to create code blocks that are executed conditionally based on those expressions. Then you'll see a couple of shortcuts and extras that C# contains to make using certain types of common logic statements even easier.
A Boolean expression is a code statement that will eventually evaluate to either
true
or
false
At the most basic level, all Boolean expressions, no matter how long or complex, are still going to evaluate to either
true
or
false
.
This expression will evaluate to
false
because 2 is not equal to 4. It can also be something complex, such as
MyObject.MyProperty == YourObject.YourProperty
This expression could evaluate to anything, and would be determined at runtime. If you are familiar with C, C++, or even C#, you know that the == (double-equals) is a logical Boolean operator, and the = (single equals) is an assignment operator used to set values. A common source of runtime and compile-time errors revolves around using these operators in the wrong place.
Table 2.1 shows the logical operators available in the C# language and provides a brief description of their purpose.
Table 2.1. C# Logical Operators
|
Operator
|
Description
|
|
&&
|
A Boolean AND operator. Expressions involving this operator will evaluate to
true
if
both
the expression on the left side of the operator
and
the expression on the right side of the operator evaluate to
true
.
|
|
|
A Boolean OR operator. Expressions using this operator will evaluate to true if
either
the
left
expression or the
right
expression are true, or if
both
expressions are true.
|
|
!
|
The NOT operator. It negates the Boolean value of whatever expression it is applied to. So, if
!
is applied to a true expression, the expression will become false. Likewise, if
!
is applied to a false expression, the expression will become true.
|
|
^
|
The exclusive OR operator (often referred to as XOR in many languages). This functions the same way as the standard OR () operator, with the exception that if
both
sides of the expression are true, this operator will return
false
|
|
~
|
This operator
performs
a bitwise complement on its operand. This means that it will reverse every single bit in whatever operand is supplied. On a single-bit value, it is the same as the
!
operator. However, on
numbers
such as integers, decimals, and so on, it has a more profound effect.
|
|
&
|
The bitwise AND operator. Instead of performing an AND against two Boolean expressions, it performs it against two numeric values. The numbers are lined up, and the AND is performed against each bit. The result of this operation is a new number. Bitwise logic has very specific uses, often when storing long lists of Boolean values as numbers.
|
|
|
The bitwise OR operator. As with the bitwise AND operator, it performs an OR operation against each bit of the two operands supplied for the expression, the result being returned as a numeric value.
|
Using Basic Conditional Statements
In the
preceding
section you were introduced to the tools you need in order to form Boolean expressions. These will allow you to assert whether or not an expression is true. When you have such an assertion, you need to be able to provide some conditional statements in your code to allow you to do something meaningful based on the results of a Boolean expression. This section will show you the basic conditional statements that are at the heart of almost all logic code in C#.
Using
If/Else Statements
The format of an
if
statement is as
follows
:
if (
expression
)
code_block
else if (
expression_1
)
code_block
else if (
expression_2
)
code_block
else
code_block
Both the
else if
and
else
sections are optional, and are only required if you want your code to perform alternate
tasks
when the original Boolean expression
evaluates
to
false
.
Because each of the code blocks in the preceding example can also contain their own
if
statements, you can nest your conditional code nearly as deep as you like. However, good style and etiquette recommend that you avoid deep nesting because it makes your code difficult to read and analyze.
The following sample
if
statements
illustrate
using
if
simply, nested, and with
else
statements:
if ( strInput == "Hello" )
Console.WriteLine("You said Hello");
if ( strInput2 == "Goodbye" )
Console.WriteLine("You said Goodbye");
else if ( strInput2 == "Later" )
Console.WriteLine("You didn't say goodbye, you said Later.")
else
{
if (strInput3 == "Hola")
if (strInput4 == "Senor")
Console.WriteLine("Hello!");
}
Using the
Switch
Statement
If you want to test a single variable against a list of possible values using just the standard
if/else
keywords, you will end up with code that looks like the following:
if (val == 1)
...
else if (val == 2)
...
else if (val == 3)
...
else if (val == 4)
...
else
...
Although this may get the job done, it's not the most elegant or the most easily readable block of code. For this situation, C# has the
switch
statement, which allows you to combine several logic tests into a single expression, as shown in the following example:
switch (val)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
default:
...
}
Using the
Goto
Statement
The
goto
statement has two main uses; one is to transfer control from one
case
within a
switch
statement, and the other is to break out of loops. You will see more on
loops
later in this chapter.
The following is a sample of a
switch
statement that utilizes the
goto
keyword for transferring control:
switch (val)
{
case 1:
...
break;
case 2:
...
goto case 1;
break;
case 3:
...
goto case 1;
break;
default:
...
}
Using Advanced Conditional Statements
One of the most common uses for an
if/else
statement is to conditionally print something or render something through Windows Forms or Web Forms. For example, suppose that you want to print the word "Good" if the profit margin is greater than 20, or "Bad" if the profit margin is less than or equal to 20. You might use an
if/else
that looks like the following:
if (profitMargin > 20)
Console.WriteLine("The profit margin is Good!");
else
Console.WriteLine("The profit margin is Bad!");
This is
perfectly
fine, but C# includes a ternary operator called the
conditional
operator that allows you to embed an
if/else
combination in a single line. You can rewrite the preceding code segment in a single line as follows:
Console.WriteLine("The profit margin is " + (profitMargin > 20) ? "Good" : "Bad");
The ternary conditional operator has the following format:
expression ? return_when_true : return_when_false