Discovering Visual Basic .NET: Making Decisions

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:

Imports System
Imports Microsoft.VisualBasic

Module SpinTheWheel
   Public Sub Main()
      Dim Wheel, Won As Integer
      Randomize
      Console.WriteLine("I'm looking for a 3")
      Console.WriteLine("and spinning the wheel!")
      Wheel = Int(Rnd * 5) + 1    ' Random number: 1-5
      Console.WriteLine("The Wheel landed on " & Wheel)
      If Wheel = 3 Then
      Won = 50
         Console.WriteLine("It landed on my number!")
         Console.WriteLine("I win $" & Won)
         End If
      Console.WriteLine("All done.")
   End Sub
End Module

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

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

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:

Imports System
Imports Microsoft.VisualBasic

Module PassFail
   Public Sub Main()
      Dim Grade As Integer
      Randomize
      Grade = Int(Rnd * 100) + 1 ' Random - between 1 and 100
      Console.WriteLine("Your grade is " & Grade)
      If Grade >= 60 Then
         Console.WriteLine("You passed!")
      Else
         Console.WriteLine("You failed...")
      End If
   End Sub
End Module

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:

Imports System
Imports Microsoft.VisualBasic

Module PercentageToLetter
   Public Sub Main()
      Dim Grade As Integer
      Dim LetterGrade As String
      Randomize
      Grade = Int(Rnd * 100) + 1    ' Random - between 1 and 100
      Console.WriteLine("Your grade is " & Grade)
      If Grade >= 90 Then
         LetterGrade = "A"
         Console.WriteLine("You got an A! Congratulations.")
      End If
      If Grade >= 80 And Grade < 90 Then
         LetterGrade = "B"
         Console.WriteLine("You got a B. Good job.")
      End If
      If Grade >= 70 And Grade < 80 Then
         LetterGrade = "C"
         Console.WriteLine("You got a C. Not bad.")
      End If
      If Grade >= 60 And Grade < 70 Then
         LetterGrade = "D"
         Console.WriteLine("You got a D. Try harder...")
      End If
      If Grade < 60 Then
         LetterGrade = "F"
         Console.WriteLine("You failed. I'm sorry.")
      End If
   End Sub
End Module

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:

Imports System
Imports Microsoft.VisualBasic

Module PercentageToLetter
   Public Sub Main()
      Dim Grade As Integer
      Dim LetterGrade As String
      Randomize
      Grade = Int(Rnd * 100) + 1    ' Random - between 1 and 100
      Console.WriteLine("Your grade is " & Grade)
      If Grade >= 90 Then
         LetterGrade = "A"
         Console.WriteLine("You got an A! Congratulations.")
      ElseIf Grade >= 80 Then
         LetterGrade = "B"
         Console.WriteLine("You got a B. Good job.")
      ElseIf Grade >= 70 Then
         LetterGrade = "C"
         Console.WriteLine("You got a C. Not bad.")
      ElseIf Grade >= 60 Then
         LetterGrade = "D"
         Console.WriteLine("You got a D. Try harder...")
      Else
         LetterGrade = "F"
         Console.WriteLine("You failed. I'm sorry.")
      End If
   End Sub
End Module

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:

  1. 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.
  2. 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?
  3. Likewise for the third and fourth conditions.
  4. 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.

Discovering Visual Basic .NET: Making Decisions

Get Off My Case!

Like the If...Then statement, the Select Case statement is used for decision-making. Select Case enables you to do various comparisons against one variable that you use throughout the whole statement.

A simple case

Here's a simple Select Case statement that checks an employee's status and displays the result to the user:

Imports System
Imports Microsoft.VisualBasic

Module PercentageToLetter
   Public Sub Main()
      Dim EmployeeStatus as String

    EmployeeStatus = "L"

      Select Case EmployeeStatus
         Case "G"
            Console.WriteLine("Employee is in good standing.")
         Case "L"
            Console.WriteLine("Employee is on leave.")
         Case "F"
            Console.WriteLine("Employee no longer works here.")
      End Select
   End Sub
End Module

Here's how this Select Case statement works:

  1. Always begin your Select Case statements with the words Select Case. (Easy enough?)
  2. After that comes a variable name. Here, the variable is EmployeeStatus. This variable is used throughout the rest of the Select Case statement.
  3. 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.
  4. 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.
  5. 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:

Imports System
Imports Microsoft.VisualBasic

Module PercentageToLetter
   Public Sub Main()
      Dim Grade As Integer
      Dim LetterGrade As String
      Randomize
      Grade = Int(Rnd * 100) + 1    ' Random number - 1 and 100
      Console.WriteLine("Your grade is " & Grade)
      Select Case Grade
         Case Is >= 90
            LetterGrade = "A"
            Console.WriteLine("You got an A! Congratulations.")
         Case Is >= 80
            LetterGrade = "B"
            Console.WriteLine("You got a B. Good job.")
         Case Is >= 70
            LetterGrade = "C"
            Console.WriteLine("You got a C. Not bad.")
         Case Is >= 60
            LetterGrade = "D"
            Console.WriteLine("You got a D. Try harder...")
         Case Else
            LetterGrade = "F"
            Console.WriteLine("You failed. I'm sorry.")
      End Select
   End Sub
End Module

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.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Agile methodologies give development and test teams the ability to build software at a faster rate than ever before. Combining DevOps with hybrid cloud architectures give teams not just the principles, but also the technology necessary to achieve their goals. By combining hybrid cloud and DevOps: IT departments maintain control, visibility, and security Dev/test teams remain agile and collaborative Organizational barriers are broken down Innovation and automation can thrive Download this white paper to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds