Write concise code with the Choose function

The Choose function lets you often make more concise, albeit not faster, code, because it lets you replace a lengthy Select Case block. For example, the following code:

Select Case index    Case 1        result = 100    Case 2        result = 250    Case 3        result = 400    Case 4        result = 500End Select

can be replaced by the more concise:

result = Choose(index, 100, 250, 400, 500)

If the index is less than one or higher than the number of values, the Choose function returns Null. Here’s another way to use the Choose function in place of a If…ElseIf block:

' the standard wayIf x < y Then    result = 100Elseif x = y Then    result = 150Else    result = 400End If' the more concise wayresult = Choose(Sgn(x - y) + 2, 100, 150, 400)

Finally, the Choose function is often useful to quickly initialize an array of number or strings:

' the standard wayDim names(1 To 5) As Stringnames(1) = "Robert"names(2) = "Patrick"names(3) = "Timothy"names(4) = "James"names(5) = "Frank"' the more concise wayDim names(1 To 5) As String, i As IntegerFor i = 1 To 5    names(i) = Choose(i, "Robert", "Patrick", "Timothy", "James", "Frank")Next

It is evident that the more array elements you must initialize, the more code you save using this technique.

However, in all cases you should keep in mind that the Choose function is always slower than the Select Case or If block it is meant to replace, therefore it shouldn’t be used in time-critical loops.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS