473,698 Members | 2,134 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 19046
"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
8094
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
1942
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
2198
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
19737
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 allows static or integral variables. For example, I often want to use a switch statement based on the...
3
2165
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
3152
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
1568
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
2880
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 me, than I pass on the code to a function that save(update) the data to the database.
5
2143
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
8674
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8861
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7721
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4366
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4615
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
1999
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.