How to use an array variable as a case parameter
Good morning all!
VS2010
.NET 3.5
Here is a snippet in VB.Net that works, but the C# version does not.
VB.Net:
Code:
Dim a(8) As String
Dim b As String
Dim c As Short
a(0) = "There"
a(1) = "Not Here"
a(2) = "Over Here"
b = "Not Here"
Select Case b
Case a(0)
c = 1
Case a(1)
c = 2
Case a(2)
c = 3
End Select
The C# code:
The Case a[x]: is the problem.
I'm getting an error: "A constant value is expected".
Code:
string a = new string[8];
string b;
int c;
a[0] = "There";
a[1] = "Not Here";
a[2] = "Over Here";
b = "Not Here";
switch (b)
{
case a[0]:
c = 1;
break;
case a[1]:
c = 2;
break;
case a[2]:
c = 3;
break;
}
Can anyone help?
Re: How to use an array variable as a case parameter
Yup, the switch only allows constant values. If it did not then it would not be nearly as performant as currently the compiler can use a jump list. I'm not a VB guy, but if VB allows such thing that is a questionable decision IMO. You can already use if() { } else if() { } for this situation, so... use that.
Re: How to use an array variable as a case parameter
Yes Vb seems to treat a select case block as though it were a group of If .. ElseIf. It is easier to read in the editor that a group of If elseif but I think the result is about the same.
Re: How to use an array variable as a case parameter
Thanks,
I will conform!
I mean, I will make the changes using the If..ElseIf statements!
Re: How to use an array variable as a case parameter
Alternatively you could define an enum; see MSDN link.
DataMiser, I think the switch statement performs substantially better than If...Elseif...Else...End constructs due to some compiler optimizations. Best case, it's a jump table; worst case its if...elseif...end. I think it's been discussed elsewhere on the forum (and on StackOverflow). I can find the reference if you're interested.
Re: How to use an array variable as a case parameter
Note: A bit off-topic, sry.
@DataMiser & BioPhysEngr: Are you both taking about VB.NET?
If I understood DataMiser correctly, when the Select Case statement is used like that in VB, then it's treated as syntactic sugar for If...Else If...ElseIf...?
Re: How to use an array variable as a case parameter
I think BioPhysEngr was referring to C# there is no switch in VB. At least not that I am aware of.
I was referring to the Select Case in VB behaving like the If ElseIf block. As you say kind of a syntactic sugar.
For example when a case within a select case statement evaluates to true the code within the case is executed and the code exits the select case block just as it would if you build a big block of If ElseIf whereas in C# you must add the break; to get it to exit.
I have not actually tested the performance of Select case compared to If ElseIf but I would not be surprised if the compiled code were exactly the same.