Select Case

The preceding section makes it clear that the If statement is the king of conditionals. However, in another scenario you may have a simple condition that needs to be tested repeatedly. For example, suppose a user selects a value from a drop-down list and different code executes depending on that value. This is a relatively simple comparison, but if you have 20 values, then you would potentially need to string together 20 different If Then and ElseIf statements to account for all of the possibilities.

A cleaner way of evaluating such a condition is to leverage a Select Case statement. This statement was designed to test a condition, but instead of returning a Boolean value, it returns a value that is then used to determine which block of code, each defined by a Case statement, should be executed:

Select Case i Case 1

'Code A1 Case 2

'Code B2 Case Else 'Code C3 End Select

The preceding sample code shows how the Select portion of the statement determines the value represented by the variable i. Depending on the value of this variable, the Case statement executes the appropriate code block. For a value of 1, the code in block A1 is executed; similarly, a 2 results in code block B2 executing. For any other value, because this Case statement includes an Else block, the Case statement executes the code represented by C3. Note that while in this example each item has its own block, it is also possible to have more than a single match on the same Case. Thus Case 2, 3 would match if the value of i were either a 2 or a 3. Finally, the next example illustrates that the cases do not need to be integer values, and can, in fact, even be strings:

Dim mystring As String = "Intro" Select Case mystring Case "Intro" 'Code A1 Case "Exit"

'Code A2 Case Else

'Code A3 End Select

Now that you have been introduced to these two control elements that enable you to specify what happens in your code, your next step is to review details of the different variable types that are available within Visual Basic 2010, starting with the value types.

VALUE TYPES (STRUCTURES)

Value types aren't as versatile as reference types, but they can provide better performance in many circumstances. The core value types (which include the majority of primitive types) are Boolean, Byte, Char, DateTime, Decimal, Double, Guid, Int16, Int32, Int64, SByte, Single, and TimeSpan. These are not the only value types, but rather the subset with which most Visual Basic developers consistently work. As you've seen, value types by definition store data on the stack.

Value types can also be referred to by their proper name: structures. The underlying principles and syntax of creating custom structures mirrors that of creating classes, covered in the next chapter. This section focuses on some of the built-in types provided by the .NET Framework — in particular, the built-in types known as primitives.

Was this article helpful?

0 0

Post a comment