O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

Switch Function

Class

Microsoft.VisualBasic.Interaction

Syntax

Switch(expr-1, value-1[, expr-2, value-2 ... [, _
       expr-n,value-n]])
expr (required; Object)

A number of expressions to be evaluated

value (required; Object)

An expression or value to return if the associated expression evaluates to True

Return Value

An Object value or expression

Description

Evaluates a list of expressions and, on finding the first expression to evaluate to True, returns an associated value or expression

Rules at a Glance

  • A minimum of two expression/value pairs is required; additional pairs are optional.

  • Expressions are evaluated from left to right.

  • If none of the expressions is True, the Switch function returns Nothing.

  • If multiple expressions are True, Switch returns the value that corresponds to the first True expression.

  • value can be a constant, variable, or expression.

Example

The GetTextColor function uses the Switch function to return an RGB color value that depends on the sign of the integer passed to it as a parameter. To access the Color structure, it imports the System.Drawing namespace of the Base Class Library.

Private Function GetTextColor(lValue As Integer) As Integer

Dim fColor As New Color
Dim iColor As Integer 
fColor = Switch(lValue > 0, Color.Blue, _
                lValue = 0, Color.Black, _
                lValue < 0, Color.Red)

' Convert color name to RGB color and strip out
' high order byte of high-order word
iColor = fColor.ToArgb and &H00FFFFFF
GetTextColor = iColor

End Function

Programming Tips and Gotchas

The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required