Discovering Visual Basic .NET: Making Decisions

WEBINAR:On-Demand

In the previous article in this series, you discovered functions arguments and and how they work. In this article, I'll show you how to make your programs smarter by letting them make their own decisions.

Your programs can make decisions on their own based on information they gather. But first, you have to tell your programs which decisions to make and how to make them. The keywords you use to do that, naturally enough, are If and Then:

If condition Then
statement
End If

This If...Then structure is often called a conditional. A conditional has two parts:

The condition, or the
question part

The statement, or the thing-to-do part

The End If just tells you when the statement part is over.

Here's an example. The computer spins a wheel that has five sections numbered 1 through 5, and I bet on number 3 coming up:

First, I display a little text to explain the premise of the game. I spin the wheel by generating a random number between 1 and 5. Then, I display the value that the wheel landed on. (For more information on Randomize, Rnd, and this formula used to generate random numbers, see the previous article in this series.)

Next up is the If...Then statement. The condition part of the If...Then asks the question, "Does the Wheel variable hold a value that equals 3?" Everything between the Then and the End If is the statement portion. If the condition is true, the statement portion is performed. If the condition is not true, the statement portion is ignored. So, in this case, if Wheel equals 3, two things happen:

The Won variable is set to 50.

The program displays this:

It landed on my number!
I win $50

Now, if you haven't already, try out this example. Run it several times so that you can see what it does both in a win and a lose scenario.

Note: If you keep running the program, you'll notice that the Won variable doesn't accumulate an additional $50 every time you win. That's because the variable is reset every time you run the program.

Discovering Visual Basic .NET: Making Decisions

WEBINAR:On-Demand

Inequalities

If...Then statements can use what math professors call inequalities. Inequalities are ways of comparing numbers to see if they are greater than or less than each other. And, to keep it simple, VB.NET uses the same symbols as you did in your sixth-grade math class:

This symbol means greater than: >

And this symbol means less than: <

How do you keep them straight? My sixth-grade teacher explained it to me this way: Think of the symbol as an alligator's big mouth opening. And just remember, the alligator always eats the bigger number. Silly? Yes. But I've never forgotten it!

Here's an example that shows how inequalities work in an If...Then statement:

Imports System
Imports Microsoft.VisualBasic
Module GetAnA
Public Sub Main()
Dim Grade As Integer
Grade = 95
If Grade > 90 Then
Console.WriteLine("You get an A!")
End If
End Sub
End Module

The happy result:

You get an A!

Because the variable Grade holds a value greater than 90, the message You get an A! appears. Suppose you don't get greater than 90, but you get 90 right on the nose. Shouldn't that be an A, too?

Try changing the preceding code so that Grade = 90. Save, compile and run. Nothing. It doesn't work. How do you fix that? Well, here's one way: Change the If...Then line to look like this:

If Grade > 89 Then

This makes the program work, but sticking with round numbers really makes more sense. A better way would be to use another symbol, >=, which means greater than or equal to.

Change the If...Then line so that it looks like this:

If Grade >= 90 Then

That's better.

You get an A!

As you may expect, you also can use a <= symbol, which means less than or equal to. These symbols are a little different from the ones you learned in sixth-grade math, but these are easier to remember anyway.

You can use one more symbol to compare variables: <>, which means does not equal. Here's an example:

If Grade <> 100 Then
Console.WriteLine("You did not get a perfect score.")
End If

Discovering Visual Basic .NET: Making Decisions

WEBINAR:On-Demand

Creating a Compound If...Then

You can also use what programmer-types like to call a logical expression in an If...Then condition. This simply means that you can put more than one question together inside the same condition by using an And or an Or to separate them. This creates a compound If...Then statement.

A compound If...Then statement works just like you may expect. If an And separates the two conditions, the statement succeeds only if both conditions are true. If either one or both is false, the statement portion is ignored. If an Or separates the two conditions, the statement succeeds if either condition (or both) is true.

You can connect together as many conditions as you like as long as an And or an Or separates each condition from the others:

If Temperature <= 32 And Liquid = "Water" Then
Console.WriteLine("Looks like ice...")
End If

Of course, too many conditions can make your statement very confusing. When you're writing programs, one rule always applies: As much as possible, keep it simple!

As I Was Saying: Line Continuation

This section is a quick digression on a topic that doesn't directly have anything to do with conditions, but can be useful when your lines get really long (whether the line is an If...Then statement or not).

You can break your line in two without confusing VB.NET into thinking it's supposed to treat that code as two separate lines. Here's an example:

If Weekday(Today) > 3 And
_ Weekday(Today) < 6
Then

You find the underscore character ( _ ) on your keyboard on the same key as the dashjust press Shift along with it. The underscore at the end of the line tells the VB.NET to consider the next line as an extension of this one.

Although you may often use the underscore with a compound If...Then, that's not the only place. In fact, you can use it in any statement. Just place the underscore in the line just before you break it. You can break a line anywhere you'd normally put a space.

If you use the underscore, indent the second line three spaces or so to make it clear that the second line is a continuation of the previous line.

In some cases, you may want to break a long string and put part of it on a second line. You can use the underscore character to do that, too, but you also need to use the & concatenation character with it:

Desc = "This is a " & _
"long description."

You put a final quote at the end of the string on the first line and a new string with quotes around it on the second line. You still need the underscore, but you also need the & to join the two strings together.

What to Do if It Isn't True

In the previous sections of this article, all the If....Then statements only tell the computer what to do if a condition is true. What if you want it to do something else when the condition is not true? That's where Else comes in:

Run this program several times until you see both passing and failing results.

Handling Multiple Conditions

You can ask one question; why not more? Of course, you can always just write one If...Then statement after another. For example, if you want to translate a percentage grade to a letter grade, you may write code that looks like this:

The preceding code works fine. But it has a couple of big problems: It's wordy, and you end up repeating yourself a lot. To make the process easier, VB.NET includes another statement to help you in situations like this: ElseIf. If you use ElseIf, your program begins to look simpler and is easier to understand:

Now the whole thing is part of one big, long If...Then. You know that because the code has only one End Ifall the way at the end.

Here's the way this If...Then...ElseIf works:

If the Grade is greater than or equal to 90, the
LetterGrade variable is set to A, the user is informed, and then the statement
ends. The rest of the conditions are ignored after a condition is met.

If the first condition is false, the second condition
is checked. Here, you only have to check whether the Grade is 80 or better.
You don't have to specify that it is less than 90 because if it had been 90 or
greater, you wouldn't be executing this condition. Right?

Likewise for the third and fourth conditions.

If you get through all the conditions and you still don't have a match, the Else catches everything elsewhich, in this case, is bad news.

After that comes a variable name. Here, the variable
is EmployeeStatus. This variable is used throughout the rest of the Select
Case statement.

Next comes a series of lines that each contain the
word Case followed by a value. Select Case automatically compares the first
value ("G") to the variable at the beginning of the Select Case statement
(EmployeeStatus) to see if they are equal.

If the first value is equal to the variable at the
beginning, the line after Case "G" and before Case "L" is executed. After that
line is finished, the statement is done and any other Case lines are ignored.
Anything after the End Select gets processed next.

If the first value isn't equal to the variable at the top, the next Case statement is checked (Case "L") and that value is compared with the variable at the beginning (again, EmployeeStatus). If a match exists, the lines under Case "L" are executed. If not, VB.NET proceeds to the next Case statement.

It's possible that none of the Case statements may match. If that happens, none of the lines within the Select Case get executed, and you just go on after the End Select. This situation would happen in the preceding statement if the EmployeeStatus was something other than "G," "L," or "F."

Notice that you don't need to repeat the variable name or even the equal sign again and again as you would in an If...Then...ElseIf. Both are automatically assumed. This strategy makes the Select Case much cleaner and easier to understand if you are continually comparing against one variable.

A tougher case

The Select Case statement is very flexible. It can do more than simple checks for equality. Like If...Then statements, it can do inequalities (with the <, >, <=, >=, and <> operators).

Here's the letter grade calculator I demonstrate earlier in this article. However, instead of using If...Then...ElseIf, I've converted the code to use Select Case:

Notice that, when comparing to see if something is equal in a Select Case, you only have to put the value on the Case line:

Case "G"

However, when you check for inequality, you have to use the keyword Is and you have to include the inequality operator you want to use:

Case Is >= 90

Using the keyword Is here may seem odd, but that's how it works!

You also can do some other fancy comparisons in the Case line. For example, if you were checking a value that could be any integer between 1 and 6, you might have a case line that looks like this:

Case 3 To 6

This will match if the variable is 3, 4, 5, or 6.

If you want to specify several values, use commas:

Case 2, 4, 6, 8

You can even combine the two techniques:

Case 1,3, 4 To 6

This would match on 1, 3, 4, 5, or 6.

When Should You Use Select Case Instead of If...Then...ElseIf?

As you may have noticed, you can create an If...Then...ElseIf that works very much like a Select Case statement, and vice versa. So, which one should you use?

In some cases, it doesn't matter. You can use either one. But, remember that If...Then...ElseIf is more flexible. Select Case restricts you to doing comparisons to only one value—the one that comes after Select Case. In an If...Then...ElseIf, you can use compound conditions to compare against two or three values, or as many as you like.

So, if you're doing several comparisons against one variable, using the Select Case is probably easier. But, if you need to do more complex comparisons, resort to If...Then...ElseIf.

In some computer languages, the Select Case statement actually runs faster than an If...Then...ElseIf. If you have programmed in C or C++, you know that this is true for those languages—and because of that factor, you are encouraged to use Select Case whenever possible. In VB.NET, you'll find no significant difference in execution speed between the two statements. So, use whichever makes your code easier to understand.

Summary

In this installment, you raised the IQ of your programs significantly by showing them how to make decisions on their own with If...Then...Else and Select Case statements. In the next article, you'll discover how loops can do the heavy lifting for calculations and a host of other tasks.

About the Author

Bill Hatfield

Bill Hatfield is the best-selling author of numerous books for developers, including ASP.NET For Dummies, Active Server Pages For Dummies (on Classic ASP) and Visual InterDev For Dummies. He is also the editor of Visual Studio .NET Developer, a monthly technical journal from Pinnacle. He's an experienced corporate trainer and works in Indianapolis, IN where he also co-founded the local .NET group, the Indianapolis .NET Developers Association.

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.

Thanks for your registration, follow us on our social networks to keep up-to-date