A casing technique in Visual Basic coding
One of famous common easy techniques in Visual Basic casing structures which is familiar to most of Visual Basic developers is the ability to compare a value with several variables in Select Case statements.
It has been pointed many times but as I saw the lack of this technique in someone’s code write about it again here.
The base point is “You can compare a constant value with several variables instead of comparing a variable with several values”. Take a look at following code in a Windows Console application. It simply gets three string values and wants to compare each variable with a constant string value. If it could find any equivalent string, will show a MessageBox with the name of the variable contains that string. Probably it’s not a real world sample but can show my purpose.
Sub Main()
Dim String1, String2, String3 As String
Console.WriteLine("Enter String1:")
String1 = Console.ReadLine()
Console.WriteLine("Enter String2:")
String2 = Console.ReadLine()
Console.WriteLine("Enter String3:")
String3 = Console.ReadLine()
If (String1 = "That's me!") Then
MsgBox("String1")
End If
If (String2 = "That's me!") Then
MsgBox("String2")
End If
If (String3 = "That's me!") Then
MsgBox("String3")
End If
End Sub
For three variables, I used three If cases to check their values. for three variables it seems to have no problem but if you want to check more variables your code won’t be logical, won’t have good structure and will have many lines. By using this technique you can replace above code with below code which is simpler and meaningful and for more variables will have shorter lines.
Sub Main()
Dim String1, String2, String3 As String
Console.WriteLine("Enter String1:")
String1 = Console.ReadLine()
Console.WriteLine("Enter String2:")
String2 = Console.ReadLine()
Console.WriteLine("Enter String3:")
String3 = Console.ReadLine()
Select Case "That's me!"
Case String1
MsgBox("String1")
Case String2
MsgBox("String2")
Case String3
MsgBox("String3")
End Select
End Sub
That’s it! This is one of famous Visual Basic coding techniques but still there are many developers who miss it. Try it in C# to know why it’s sharp!
Now playing: Pink Floyd - Mother
[advertisement] Axosoft OnTime 2008 is four developer tools in one: bug tracking, project wiki, feature management, and help desk. It manages your development process so developers can focus on coding. Installed or Hosted – Free Single-user license -- Free 30-day team trial.
13 Comments : 07.16.06

#1
J-O Eriksson
07.16.2006 @ 1:47 PM