473,575 Members | 3,401 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

switch vs Select Case

ME
In C# the following code generates a compiler error
("A constant value is expected"):

public void Test(string value)
{
switch (value)
{
case SimpleEnum.One. ToString():
MessageBox.Show ("Test 1");
break;
case SimpleEnum.Two. ToString():
MessageBox.Show ("Test 2");
break;
case SimpleEnum.Thre e.ToString():
MessageBox.Show ("Test 3");
break;
}
}

The Visual Basic.NET version does not:

Public Sub Test(ByVal value As String)
Select Case value
Case SimpleEnum.One. ToString()
MessageBox.Show ("Test 1")
Case SimpleEnum.Two. ToString()
MessageBox.Show ("Test 2")
Case SimpleEnum.Thre e.ToString()
MessageBox.Show ("Test 3")
Case Else
End Select
End Sub
How can this be done in C# and also why is this true?
Feb 11 '06 #1
16 19032
"case" expressions must be constants in C#. As soon as you use
"ToString" you are using a method result, which is variable by
definition.

Anyway, in both VB.NET and C# I wouldn't do it that way. To me, you
have it flipped around backward. You're better off converting the
string to the enumeration, and then doing the switch. The only extra
code is to catch errors:

public void Test(string value)
{
try
{
SimpleEnum enumVal = Enum.Parse(type of(SimpleEnum), value,
false);
switch (enumVal)
{
case SimpleEnum.One: MessageBox.Show ("Test 1"); break;
case SimpleEnum.Two: MessageBox.Show ("Test 2"); break;
case SimpleEnum.Thre e: MessageBox.Show ("Test 3"); break;
default:
MessageBox.Show (String.Format( "Added new enum {0}
without modifying switch", enumValue);
break;
}
}
catch (ArgumentExcept ion)
{
MessageBox.Show (String.Format( "String {0} is not a
SimpleEnum.", value);
}
}

Feb 11 '06 #2
Clearly VB.NET is not as strict about what can be tested. My suspicion
is that a C# switch, if you can live within its requirements, is faster,
although I doubt it matters in the real world very often.

A C# construct like the following will do what you want:

if (value == SimpleEnum.One. ToString()) {
MessageBox.Show ("Test 1");
} else if (value == SimpleEnum.Two. ToString()) {
MessageBox.Show ("Test 2");
} else if (value == SimpleEnum.Thre e.ToString()) {
MessageBox.Show ("Test 3");
} else {
MessageBox.Show ("Default Test");
}

--Bob

ME wrote:
In C# the following code generates a compiler error
("A constant value is expected"):

public void Test(string value)
{
switch (value)
{
case SimpleEnum.One. ToString():
MessageBox.Show ("Test 1");
break;
case SimpleEnum.Two. ToString():
MessageBox.Show ("Test 2");
break;
case SimpleEnum.Thre e.ToString():
MessageBox.Show ("Test 3");
break;
}
}

The Visual Basic.NET version does not:

Public Sub Test(ByVal value As String)
Select Case value
Case SimpleEnum.One. ToString()
MessageBox.Show ("Test 1")
Case SimpleEnum.Two. ToString()
MessageBox.Show ("Test 2")
Case SimpleEnum.Thre e.ToString()
MessageBox.Show ("Test 3")
Case Else
End Select
End Sub
How can this be done in C# and also why is this true?

Feb 11 '06 #3
Hi,

The C# specs indicate that you should place constant expressions in case
clauses. Your calls to ToString() are not.
VB.NET Select Case is obviously more "dynamic" and calculates the expression
at runtime and then checks for equality. This scheme may look more dynamic,
but offers less opportunities for code optimization.
I think you should rewrite your method in order to receive not a string, but
a SimpleEnum parameter, which can be used later in the switch statement. It
will be safer and more efficient:

public void Test(SimpleEnum se)
{
switch (se)
{
case SimpleEnum.One:
MessageBox.Show ("Test 1");
break;
case SimpleEnum.Two:
MessageBox.Show ("Test 2");
break;
}
}

Regards - Octavio
"ME" <tr*********@co mcast.netREMOVE THIS> escribió en el mensaje
news:Pr******** ************@co mcast.com...
In C# the following code generates a compiler error
("A constant value is expected"):

public void Test(string value)
{
switch (value)
{
case SimpleEnum.One. ToString():
MessageBox.Show ("Test 1");
break;
case SimpleEnum.Two. ToString():
MessageBox.Show ("Test 2");
break;
case SimpleEnum.Thre e.ToString():
MessageBox.Show ("Test 3");
break;
}
}

The Visual Basic.NET version does not:

Public Sub Test(ByVal value As String)
Select Case value
Case SimpleEnum.One. ToString()
MessageBox.Show ("Test 1")
Case SimpleEnum.Two. ToString()
MessageBox.Show ("Test 2")
Case SimpleEnum.Thre e.ToString()
MessageBox.Show ("Test 3")
Case Else
End Select
End Sub
How can this be done in C# and also why is this true?

Feb 11 '06 #4
Not sure if this is what you are trying to do, but this works fine under 2.0
framework.

using System;

public class MyTestClass {

private enum Nums {
One = 1,
Two,
Three
}

public static void Test(string Value) {

switch(Value) {

case "One":
Console.WriteLi ne("Test One");
break;

case "Two":
Console.WriteLi ne("Test Two");
break;

case "Three":
Console.WriteLi ne("Test Three");
break;
}
}

public static int Main() {

Test(Enum.GetNa me(typeof(Nums) , Nums.Two));
Test(Enum.GetNa me(typeof(Nums) , Nums.One));
Test(Enum.GetNa me(typeof(Nums) , Nums.Three));
Test(Enum.GetNa me(typeof(Nums) , Nums.Two));

System.Console. Write("\nPress any key to continue...");
System.Console. ReadKey();

return 0;
}
}
Bye

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
"case" expressions must be constants in C#. As soon as you use
"ToString" you are using a method result, which is variable by
definition.

Anyway, in both VB.NET and C# I wouldn't do it that way. To me, you
have it flipped around backward. You're better off converting the
string to the enumeration, and then doing the switch. The only extra
code is to catch errors:

public void Test(string value)
{
try
{
SimpleEnum enumVal = Enum.Parse(type of(SimpleEnum), value,
false);
switch (enumVal)
{
case SimpleEnum.One: MessageBox.Show ("Test 1"); break;
case SimpleEnum.Two: MessageBox.Show ("Test 2"); break;
case SimpleEnum.Thre e: MessageBox.Show ("Test 3"); break;
default:
MessageBox.Show (String.Format( "Added new enum {0}
without modifying switch", enumValue);
break;
}
}
catch (ArgumentExcept ion)
{
MessageBox.Show (String.Format( "String {0} is not a
SimpleEnum.", value);
}
}

Feb 11 '06 #5
Hi Brooke,

Yes, it works the way you apply it, you use string constants, but you
can't use variables. In general practice, it's better to avoid 'magic'
string constants like these.

Bruce's way is preferable...

Wiebe

Brooke wrote:
Not sure if this is what you are trying to do, but this works fine under 2.0
framework.

using System;

public class MyTestClass {

private enum Nums {
One = 1,
Two,
Three
}

public static void Test(string Value) {

switch(Value) {

case "One":
Console.WriteLi ne("Test One");
break;

case "Two":
Console.WriteLi ne("Test Two");
break;

case "Three":
Console.WriteLi ne("Test Three");
break;
}
}

public static int Main() {

Test(Enum.GetNa me(typeof(Nums) , Nums.Two));
Test(Enum.GetNa me(typeof(Nums) , Nums.One));
Test(Enum.GetNa me(typeof(Nums) , Nums.Three));
Test(Enum.GetNa me(typeof(Nums) , Nums.Two));

System.Console. Write("\nPress any key to continue...");
System.Console. ReadKey();

return 0;
}
}
Bye

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
"case" expressions must be constants in C#. As soon as you use
"ToString" you are using a method result, which is variable by
definition.

Anyway, in both VB.NET and C# I wouldn't do it that way. To me, you
have it flipped around backward. You're better off converting the
string to the enumeration, and then doing the switch. The only extra
code is to catch errors:

public void Test(string value)
{
try
{
SimpleEnum enumVal = Enum.Parse(type of(SimpleEnum), value,
false);
switch (enumVal)
{
case SimpleEnum.One: MessageBox.Show ("Test 1"); break;
case SimpleEnum.Two: MessageBox.Show ("Test 2"); break;
case SimpleEnum.Thre e: MessageBox.Show ("Test 3"); break;
default:
MessageBox.Show (String.Format( "Added new enum {0}
without modifying switch", enumValue);
break;
}
}
catch (ArgumentExcept ion)
{
MessageBox.Show (String.Format( "String {0} is not a
SimpleEnum. ", value);
}
}


Feb 11 '06 #6
ME
I can see the enum example is throwing several off the point. Here is another EXAMPLE of a time when I would like to use a dynamic switch:

private void WorkWithSelecte dColumn(Templat eADataSet.SiteO ptionsRow row, string columnName)
{

//Switch 1 works:
switch (columnName)
{
case "Key":
break;
case "Value":
break;
case "UniqueID":
break;
}

//Switch 2 does not work in c# but the vb version will work
switch (columnName)
{
case row.Key:
break;
case row.Value:
break;
case row.UniqueID:
break;
}
}

I realize that C# requires a constant. My question is, why give the VB guys the "option" of creating a dynamic switch/select case but not give it to the C# guys? Typically the way I handle this particular example is by using SQL to generate some code constants (public constants of every column name of every table in my data base) and use those in place of the "xxx" in switch 1. It would be nice to be able to perform the task in switch 2, which would leave out a step (VS builds the dataset for me just fine).

Thanks,

Matt
"ME" <tr*********@co mcast.netREMOVE THIS> wrote in message news:Pr******** ************@co mcast.com...
In C# the following code generates a compiler error
("A constant value is expected"):

public void Test(string value)
{
switch (value)
{
case SimpleEnum.One. ToString():
MessageBox.Show ("Test 1");
break;
case SimpleEnum.Two. ToString():
MessageBox.Show ("Test 2");
break;
case SimpleEnum.Thre e.ToString():
MessageBox.Show ("Test 3");
break;
}
}

The Visual Basic.NET version does not:

Public Sub Test(ByVal value As String)
Select Case value
Case SimpleEnum.One. ToString()
MessageBox.Show ("Test 1")
Case SimpleEnum.Two. ToString()
MessageBox.Show ("Test 2")
Case SimpleEnum.Thre e.ToString()
MessageBox.Show ("Test 3")
Case Else
End Select
End Sub


How can this be done in C# and also why is this true?

Feb 12 '06 #7
I believe that the answer to the question, "Why doesn't C# allow
variables or expressions as 'case' values?" is as follows.

Languages that allow variable 'case' values, or that go even farther
and allow conditions case 'case' values, have little choice but to turn
switches with variable or conditional cases into a long sequence of if
/ then / else if / ... else statements. As such, VB.NET (for example)
is doing some magic behind the scenes to turn what looks like a switch
into something that isn't a switch at all, in order to allow the
programmer to use a more pleasing construct.

C# (and C and C++) take the attitude that what you code is what you
get. The language doesn't play monkey business behind the scenes. In
C#, a 'switch' is always a fast selection amongst alternatives. The
language might choose to generate a switch as a sequence of tests, but
only if it were faster to do it that way. In keeping with this
philosophy, the language doesn't allow you to write code that looks
like a fast selection amongst alternatives but in fact is not.
Therefore, 'case' values must be constants, so that the strategy for
deciding how to arrive at the correct case can be decided at compile
time.

Feb 13 '06 #8
Bruce Wood <br*******@cana da.com> wrote:

<snip>
C# (and C and C++) take the attitude that what you code is what you
get. The language doesn't play monkey business behind the scenes. In
C#, a 'switch' is always a fast selection amongst alternatives. The
language might choose to generate a switch as a sequence of tests, but
only if it were faster to do it that way. In keeping with this
philosophy, the language doesn't allow you to write code that looks
like a fast selection amongst alternatives but in fact is not.
Therefore, 'case' values must be constants, so that the strategy for
deciding how to arrive at the correct case can be decided at compile
time.


Ironically, C# *does* play monkey business behind the scenes when it
comes to strings, as noted elsewhere (using a Hashtable when there are
more than a few strings). Fortunately, it's still a fast selection, but
perhaps not quite as fast as might be expected.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 13 '06 #9
ME
Bruce,

I agree with your logic. So the next question I would have is why does VB
still allow it? Shouldn't the languages be close here? The diffence
between a dynamic construct(vb) and a static one could cause some major
grief if re-wrote from VB to C#. It could be said that this WOULD make C# a
better language. Isn't that what MS is trying to squash?

Thanks,

Matt
"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
I believe that the answer to the question, "Why doesn't C# allow
variables or expressions as 'case' values?" is as follows.

Languages that allow variable 'case' values, or that go even farther
and allow conditions case 'case' values, have little choice but to turn
switches with variable or conditional cases into a long sequence of if
/ then / else if / ... else statements. As such, VB.NET (for example)
is doing some magic behind the scenes to turn what looks like a switch
into something that isn't a switch at all, in order to allow the
programmer to use a more pleasing construct.

C# (and C and C++) take the attitude that what you code is what you
get. The language doesn't play monkey business behind the scenes. In
C#, a 'switch' is always a fast selection amongst alternatives. The
language might choose to generate a switch as a sequence of tests, but
only if it were faster to do it that way. In keeping with this
philosophy, the language doesn't allow you to write code that looks
like a fast selection amongst alternatives but in fact is not.
Therefore, 'case' values must be constants, so that the strategy for
deciding how to arrive at the correct case can be decided at compile
time.

Feb 14 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
8077
by: Robert Scheer | last post by:
Hi. In VBScript I can use a Select Case statement like that: Select Case X Case 1 to 10 'X is between 1 and 10 Case 11,14,16 'X is 11 or 14 or 16 End Select
6
1937
by: Aristotelis E. Charalampakis | last post by:
Hi all, this is a newbie question :-) I was wondering if there was a way to use the switch statement in a manner that each case statement includes more that a simple value. i.e.: switch ( myFloat ) { case >0: // ??? how do i write this ???
11
2185
by: Scott C. Reynolds | last post by:
In VB6 you could do a SELECT CASE that would evaluate each case for truth and execute those statements, such as: SELECT CASE True case x > y: dosomestuff() case x = 5: dosomestuff() case y > x: dosomestuff()
3
19732
by: pgraeve | last post by:
I am a convert from VB to C# so bear with me on this "conversion" question C# switch statement seems to be the closest relative to VB's Select Case. I used VB's Select Case statement liberally. Now I find myself wanting to use "Select Case" i.e., "switch" in C# regularly, but I always have to find another way b/c C#'s switch statement only...
3
2161
by: John | last post by:
Is there a way in c# to have a switch statement with multiple expressions like in VB.net? Select Case e.Item.ItemType Case ListItemType.Item, ListItemType.AlternatingItem, ListItemType.EditItem Case expression, expression2 End Select
11
3143
by: ME | last post by:
In C# the following code generates a compiler error ("A constant value is expected"): public void Test(string value) { switch (value) { case SimpleEnum.One.ToString(): MessageBox.Show("Test 1"); break;
2
1563
by: huzzaa | last post by:
I am trying to get the user to input 1-10 and that will select a a number from an array and place it into a variable. here is the code. do { cout << "Enter the first row from column 1 to be summed (1-10)"; cout << endl << endl;
2
2874
osward
by: osward | last post by:
Hello there, I am using phpnuke 8.0 to build my website, knowing little on php programing. I am assembling a module for my member which is basically cut and paste existing code section of various module that I found it useful. Here is the 1st problem I encounter: I had a function to edit a event row form the database which is fine with...
5
2131
by: richard | last post by:
I've been tossing around the idea now that maybe my problem might be better resolved by using the "select case"/switch command. The only problem is, all the dozens of sites I've seen so far only give very brief examples using the very basic things. Such as: select case name case "adam" document.write("adam")
0
7845
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8120
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8281
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7868
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8143
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6515
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3797
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1382
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1107
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.