Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Vb

Idiom #206 Switch statement with strings

Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.

Imports Microsoft.VisualBasic
CallByName(receiver, str, CallType.Method)

In VB.NET, CallByName() uses reflection, which is relatively slow, to bind the member str of the object instance receiver.
Select Case str
    Case NameOf(Foo)
        Foo()
    Case NameOf(Bar)
        Bar()
    Case NameOf(Baz)
        Baz()
    Case NameOf(Barfl)
        Barfl()
End Select

The NameOf() operator evaluates at compile-time to the name of an identifier and helps ensure correctness when refactoring.

VB identifiers are case-insensitive, but the Select Case statement is case-sensitive by default.

The
Option Compare Text statement makes Select Case compare strings case-insensitively.
(some-> str {"foo" foo "bar" bar "baz" baz "barfl" barfl} (.call))

map is a function of a key, which return value for that key, if any.

There is case, but unlike map {} it is opaque, and you can't see which functions are whitelisted in runtime.

.call is a java.util.concurrent.Callable/call

New implementation...
< >
tkoenig