-1

I'm working on my C# project, and I need to do this, but without the If, in a short way;

for (String = n) do that
for (String = s) do those
for (String = c) do this

I don't know how it's called, or how to do it without the long If functions.

nickb
  • 59,313
  • 13
  • 108
  • 143
TDT-Alpha
  • 5
  • 1
  • 5
  • 4
    `switch`? http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.80).aspx – Alex K. May 21 '13 at 15:06
  • What logical reason can there be for not using a `if else if else` conditional statement? – Security Hound May 21 '13 at 15:41
  • You probably don't want to use a `string` for this in the first place. Jumping ahead, if `String` were an `Action` you could just invoke it. – Jodrell May 21 '13 at 15:49
  • @Ramhound - because the IF thingies take A LOT of code lines, which are a mess... As people guided me - Switches are fast, short and WORKING. I had too many bugs using IF statements – TDT-Alpha May 22 '13 at 11:58

2 Answers2

2

You can simply use a switch statement:

switch (myString) {
    case "n":
        //...
        break;
    case "s":
        //...
        break;
    case "c":
        //...
        break;
}

But be aware that the used case-strings are constants and case-sensitive!
Be also aware that using myString.ToLower() is dangerous!

If case-sensivity is a problem, you have to use ifs:

if (string.Compare(myString, "abc", true)==0)) {
    //...
}
else if (string.Compare(myString, "123", true)==0)) {
    //...
}
joe
  • 8,344
  • 9
  • 54
  • 80
  • "the strings are ... not case-sensitive" (sic). Can you back that statement up please? C# **is** case sensitive for string comparison using `==`, and `switch` is [no](http://stackoverflow.com/questions/2334134/how-to-make-the-c-sharp-switch-statement-use-ignorecase) [different](http://stackoverflow.com/questions/5986694/cs-switch-statement-is-case-sensitive-is-there-a-way-to-toggle-it-so-it-becom) – Andy Brown May 21 '13 at 15:45
  • @AndyBrown: sorry, my bad! – joe May 21 '13 at 15:46
  • Thanks! this is what I was searching for ^_^ – TDT-Alpha May 21 '13 at 17:06
1

You can use switch, e.g. for a variable called myString:

switch (myString) {
  case "n":
    doThat();
    break;
  case "s":
    doThose();
    break;
  case "c":
    doThis();
    break;
  default:
    doNothing();
    break;
}

The default case is there in case your myString is none of the values you have taken account of in your specific case statements.

Andy Brown
  • 18,961
  • 3
  • 52
  • 62