Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 2: Learning Just Enough C# or VB.NET: Basic Syntax 55
The Ternary and Immediate If Operators
The C# ternary and VB immediate if operators allow you to test a condition and return
a different value depending on whether that condition is true or false. Listing 2-2 shows
how the ternary and immediate if operators work.
Listing 2-2 A ternary operator example
C#:
int bankAccount = 0;
string accountString = bankAccount == 0 ? "checking" : "savings";
VB:
Dim accountString As String =
IIf(bankAccount = 0, "checking", "saving")
The conditional part of this operator evaluates if bankAccount is equal to 0 or not
when the program runs (commonly known as “at runtime”). Whenever the condition is
true, the first expression, the one following the question mark for C# or following the
comma for VB, “checking” in this case, will be returned. Otherwise, if the condition
evaluates to false, the second expression, following the colon for C# or after the second
comma for VB, will be returned. That returned value, either the string “checking” or
“savings” in this case, is assigned to the accountString variable that was declared.
NOTE
In earlier versions of the VB programming language, you were required to place an
underline at the end of a statement that continued to the next line. In the latest version
of VB, line continuations are optional. If you’ve programmed in VB before, the missing
statement continuation underline might have caught your attention, but it is now
perfectly legal.
Enums
An enum allows you to specify a set of values that are easy to read in code. The example
I’ll use is to create an enum that lists types of bank accounts, such as checking, savings,
and loan. To create an enum, open a new file by right-clicking the project, select Add |
New Item | Code File, call the file BankAccounts.cs (or BankAccounts.vb), and you’ll
have a blank file. Type the enum in Listing 2-3.