Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

switch statement question 6

Status
Not open for further replies.

hedgracer

Programmer
Mar 21, 2001
186
US
I have the following code:

int iMth = DateTime.Now.Month;
int iYr = DateTime.Now.Year;
string sYear;
string sMonth;

switch (iMth)
{
case 1:
if (iMth == 1)
{
iYr = iYr - 1;
sMonth = "12";
sYear = iYr.ToString();
}
break;
case 2:
if (iMth > 1 || iMth < 10)
{
iMth = iMth - 1;
sMonth = "0" + iMth.ToString();
sYear = iYr.ToString();
}
break;
case 3:
if (iMth >= 10)
{
sMonth = iMth.ToString();
sYear = iYr.ToString();
}
break;
}

iMth is equal to 3 and iYr is equal to 2008. The trouble is that iMth is dropping through the switch statement to case 3 even though iMth is 3. I am relatively new to C# so this is a little troubling to me(C++ was several years ago). Can anyone give me some suggestions? Thanks for all help in advance.

Dave
 
whatever happened to hedgracer?

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Switch and If

I think the switch and if statements translate a bit different to binary executable. The Switch (Or Case) statement is faster than if, but less flexible. This means nothing when your working with a 2 GHz processor, but in the old days when processors where much slower, it might sometimes have mattered for realtime systems, but I am guessing about that.

What happended to headgracer? He probably figured out what was wrong with his code.......
 
The C# -> MSIL compiler (not the jitter) translates switches with odd* cases into an if/elseif/elseif .. etc ../else block.

*: such as when you have the cases 0, 3, 20 and 1000 for example. They will be ordered ascending. (I have checked this with ILDasm)

Also, considering the IL opcode of switch, it is by design impossible to switch with anything else than a constant int. Everything that is not an int will be converted to one (so watch out with longs). It is very hard, if not impossible, to have an actual string switch. In most cases you will have "odd cases" so they will be spread out into an if/elseif .. elseif/else block, such as this:

Code:
    L_000b: ldloc.1 
    L_000c: ldstr "a"
    L_0011: call bool [mscorlib]System.String::op_Equality(string, string)
    L_0016: brtrue.s L_0032
    L_0018: ldloc.1 
    L_0019: ldstr "b"
    L_001e: call bool [mscorlib]System.String::op_Equality(string, string)
    L_0023: brtrue.s L_0032
    L_0025: ldloc.1 
    L_0026: ldstr "c"
    L_002b: call bool [mscorlib]System.String::op_Equality(string, string)
    L_0030: brtrue.s L_0032
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top