I am writing some code in VB.NET that uses a switch statement but in one of the cases it needs to jump to another block. In C# it would look like this:
switch (parameter)
{
case "userID":
// does something here.
case "packageID":
// does something here.
case "mvrType":
if (otherFactor)
{
// does something here.
}
else
{
goto default;
}
default:
// does some processing...
break;
}
However, I don't know how to convert this to VB.NET. I tried this:
Select Case parameter
Case "userID"
' does something here.
Case "packageID"
' does something here.
Case "mvrType"
If otherFactor Then
' does something here.
Else
GoTo Case Else
End If
Case Else
' does some processing...
Exit Select
End Select
But when I do this I get a compiler error: "Identifier expected". There'sa squiggly line under "Case". Any ideas?
Also, is it wrong to use a GoTo statement in this case? It seems any other way I would have to re-write it.
I have changed my code to as follows:
If otherFactor AndAlso parameter = "mvrType" Then
'does something here
Else
' My original "Select Case statement" here without the case for "mvrType"
End If
Is there a reason for the goto? If it doesn't meet the if criterion, it will simply not perform the function and go to the next case.
I'm not sure it's a good idea to use a GoTo but if you do want to use it, you can do something like this:
As I said, although it works, GoTo is not good practice, so here are some alternative solutions:
Using elseif...
Using a boolean value...
Instead of setting a boolean variable you could also call a method directly in both cases...
Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.
In VB.NET, you can apply multiple conditions even if the other conditions don't apply to the Select parameter. See below: