Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. The Switch Statement

The Switch Statement

Scheduled Pinned Locked Moved C#
csscomtoolsarchitecturequestion
29 Posts 14 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    Jammer 0
    wrote on last edited by
    #1

    Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

    Jammer My Blog | Article(s)

    A P M W P 11 Replies Last reply
    0
    • J Jammer 0

      Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

      Jammer My Blog | Article(s)

      A Offline
      A Offline
      Anthony Mushrow
      wrote on last edited by
      #2

      Err, being polite, I don't agree. What if you had an enumaration of states and had to execute a different peice of code depending on the current state? You'd have two main choices a bunch of if/else's or a switch. Switch is a little neater and makes more sense so you'd use that. Of course it greatly depends on the situation, but there's absolutely nothing wrong with a switch block.

      My current favourite word is: Nipple!

      -SK Genius

      Game Programming articles start -here[^]-

      J 1 Reply Last reply
      0
      • A Anthony Mushrow

        Err, being polite, I don't agree. What if you had an enumaration of states and had to execute a different peice of code depending on the current state? You'd have two main choices a bunch of if/else's or a switch. Switch is a little neater and makes more sense so you'd use that. Of course it greatly depends on the situation, but there's absolutely nothing wrong with a switch block.

        My current favourite word is: Nipple!

        -SK Genius

        Game Programming articles start -here[^]-

        J Offline
        J Offline
        Jammer 0
        wrote on last edited by
        #3

        I agree, I just thought I'd post this here to see what people think since I was just writing a switch statement and the conversation popped back into my head. I've used a switch in a couple of places in my current project and I think its perfectly valid where I've used it. I was just wondering what the general consensus is on CP. I'm not a great fan of massive if/else's, they look ugly and are harder to read 9 time out of 10.

        Jammer My Blog | Article(s)

        1 Reply Last reply
        0
        • J Jammer 0

          Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

          Jammer My Blog | Article(s)

          P Offline
          P Offline
          Pete OHanlon
          wrote on last edited by
          #4

          A switch statement looks like an ugly hack, and some purists feel it is, but there are times when it makes more sense to use a switch than to have to write 4000 lines of plumbing code just to avoid it. It's like everything else in C# - use it when you have to.

          Deja View - the feeling that you've seen this post before.

          My blog | My articles | MoXAML PowerToys

          J J 2 Replies Last reply
          0
          • J Jammer 0

            Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

            Jammer My Blog | Article(s)

            M Offline
            M Offline
            Mark Salsbery
            wrote on last edited by
            #5

            Jammer wrote:

            if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture

            That makes so much sense considering it's been around since C and the C# founders decided to include it in C# just for bad software architects to use...yeah... :rolleyes:

            Mark Salsbery Microsoft MVP - Visual C++ :java:

            J V 2 Replies Last reply
            0
            • J Jammer 0

              Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

              Jammer My Blog | Article(s)

              W Offline
              W Offline
              Wendelius
              wrote on last edited by
              #6

              Hmm, in my opinion why would it be incorrect to use a reserved keyword that's included in a language... Of course switch is much more limited compared to if-statement, but then again if used nicely it's really readable. When reading long if-else-if-else... structures they easily take away the focus from the action that's executed if (simple) condition matches. Also in a multimatch situation, switch is very nice compared to or logic in if statements or duplicated code if or is not used. However, is switch better than if in some case would greately be a matter of writing style (clarity above all :)). Mika

              The need to optimize rises from a bad design. My articles[^]

              1 Reply Last reply
              0
              • M Mark Salsbery

                Jammer wrote:

                if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture

                That makes so much sense considering it's been around since C and the C# founders decided to include it in C# just for bad software architects to use...yeah... :rolleyes:

                Mark Salsbery Microsoft MVP - Visual C++ :java:

                J Offline
                J Offline
                Jammer 0
                wrote on last edited by
                #7

                Heh heh ... to be fair, I've been learning C# since February and it wouldn't be the first time that I've come across something in the language and other more experienced folks have said to me "oooh ... you really don't want to use that ... that's bad" or similar. And like everything there is more than one way to skin a cat. I'm sure I could design out the need for the switch statements I've used so far if I really wanted too ...

                Jammer My Blog | Article(s)

                M 1 Reply Last reply
                0
                • P Pete OHanlon

                  A switch statement looks like an ugly hack, and some purists feel it is, but there are times when it makes more sense to use a switch than to have to write 4000 lines of plumbing code just to avoid it. It's like everything else in C# - use it when you have to.

                  Deja View - the feeling that you've seen this post before.

                  My blog | My articles | MoXAML PowerToys

                  J Offline
                  J Offline
                  Jammer 0
                  wrote on last edited by
                  #8

                  Gotcha.

                  Jammer My Blog | Article(s)

                  1 Reply Last reply
                  0
                  • J Jammer 0

                    Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

                    Jammer My Blog | Article(s)

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #9

                    Yeah, what they said. Or, start using Dictionary<sometype,delegate> to simulate switches: http://www.codeproject.com/KB/tips/DictorionaryEnumDelegate.aspx[^]

                    G 1 Reply Last reply
                    0
                    • J Jammer 0

                      Heh heh ... to be fair, I've been learning C# since February and it wouldn't be the first time that I've come across something in the language and other more experienced folks have said to me "oooh ... you really don't want to use that ... that's bad" or similar. And like everything there is more than one way to skin a cat. I'm sure I could design out the need for the switch statements I've used so far if I really wanted too ...

                      Jammer My Blog | Article(s)

                      M Offline
                      M Offline
                      Mark Salsbery
                      wrote on last edited by
                      #10

                      IMO it comes down to the resulting compiled code. The ability of a computer to branch based on a decision is powerful, and taken for granted these days. So, when designing a high level language, where you want the ability to branch based on a list of comparisons, what are the alternatives? One can do it explicitly with if/then/else but that can be inefficient for the decision at the end of a big list. To avoid that inefficiency some kind of look-up table may be more efficient. Theoretically, using the switch semantics, a good compiler could recognize a big list and produce more efficient branching code - possibly using a look-up table of some kind. The restrictions of the switch statement allows this. Here's a C++ example ( completely OT for this forum, but demonstrates my point):

                      int i = 6;
                      
                      if (i == 0)
                      	TRACE0("0");
                      else if (i == 1)
                      	TRACE0("1");
                      else if (i == 2)
                      	TRACE0("2");
                      else if (i == 3)
                      	TRACE0("3");
                      else if (i == 4)
                      	TRACE0("4");
                      else if (i == 5)
                      	TRACE0("5");
                      else if (i == 6)
                      	TRACE0("6");
                      else 
                      	TRACE0("n");
                      
                      switch (i)
                      {
                      case 0:
                      	TRACE0("0");
                      	break;
                      case 1:
                      	TRACE0("1");
                      	break;
                      case 2:
                      	TRACE0("2");
                      	break;
                      case 3:
                      	TRACE0("3");
                      	break;
                      case 4:
                      	TRACE0("4");
                      	break;
                      case 5:
                      	TRACE0("5");
                      	break;
                      case 6:
                      	TRACE0("6");
                      	break;
                      default:
                      	TRACE0("n");
                      	break;
                      }
                      

                      The resulting if/else machine code does six comparisons to get to the resulting branch. The resulting switch machine code does one comparison to see if i is > 6, and if it isn't, branches directly to the correct case using only TWO machine code instructions (via a look-up table)

                      0041D9F5 mov ecx,dword ptr [ebp-0AE4h]
                      0041D9FB jmp dword ptr (41F8CCh)[ecx*4]

                      switch may be ugly in source code, but the compiler can certainly take advantage of it to produce efficient code. And I don't buy the "purist programmer" arguments...what purist would use C# (or any other higher level language)? ;) It still all comes down to knowing the language you're using and choosing the right instructions for the given situation... Mark

                      Mark Salsbery Microsoft MVP - Visual C++ :java:

                      J 1 Reply Last reply
                      0
                      • M Mark Salsbery

                        IMO it comes down to the resulting compiled code. The ability of a computer to branch based on a decision is powerful, and taken for granted these days. So, when designing a high level language, where you want the ability to branch based on a list of comparisons, what are the alternatives? One can do it explicitly with if/then/else but that can be inefficient for the decision at the end of a big list. To avoid that inefficiency some kind of look-up table may be more efficient. Theoretically, using the switch semantics, a good compiler could recognize a big list and produce more efficient branching code - possibly using a look-up table of some kind. The restrictions of the switch statement allows this. Here's a C++ example ( completely OT for this forum, but demonstrates my point):

                        int i = 6;
                        
                        if (i == 0)
                        	TRACE0("0");
                        else if (i == 1)
                        	TRACE0("1");
                        else if (i == 2)
                        	TRACE0("2");
                        else if (i == 3)
                        	TRACE0("3");
                        else if (i == 4)
                        	TRACE0("4");
                        else if (i == 5)
                        	TRACE0("5");
                        else if (i == 6)
                        	TRACE0("6");
                        else 
                        	TRACE0("n");
                        
                        switch (i)
                        {
                        case 0:
                        	TRACE0("0");
                        	break;
                        case 1:
                        	TRACE0("1");
                        	break;
                        case 2:
                        	TRACE0("2");
                        	break;
                        case 3:
                        	TRACE0("3");
                        	break;
                        case 4:
                        	TRACE0("4");
                        	break;
                        case 5:
                        	TRACE0("5");
                        	break;
                        case 6:
                        	TRACE0("6");
                        	break;
                        default:
                        	TRACE0("n");
                        	break;
                        }
                        

                        The resulting if/else machine code does six comparisons to get to the resulting branch. The resulting switch machine code does one comparison to see if i is > 6, and if it isn't, branches directly to the correct case using only TWO machine code instructions (via a look-up table)

                        0041D9F5 mov ecx,dword ptr [ebp-0AE4h]
                        0041D9FB jmp dword ptr (41F8CCh)[ecx*4]

                        switch may be ugly in source code, but the compiler can certainly take advantage of it to produce efficient code. And I don't buy the "purist programmer" arguments...what purist would use C# (or any other higher level language)? ;) It still all comes down to knowing the language you're using and choosing the right instructions for the given situation... Mark

                        Mark Salsbery Microsoft MVP - Visual C++ :java:

                        J Offline
                        J Offline
                        Jammer 0
                        wrote on last edited by
                        #11

                        Great example! Thanks for this ...

                        Jammer My Blog | Article(s)

                        M 1 Reply Last reply
                        0
                        • J Jammer 0

                          Great example! Thanks for this ...

                          Jammer My Blog | Article(s)

                          M Offline
                          M Offline
                          Mark Salsbery
                          wrote on last edited by
                          #12

                          Heh no problem. I work alone at home - I don't get to have these water-cooler discussions with colleagues :) Cheers!

                          Mark Salsbery Microsoft MVP - Visual C++ :java:

                          J 1 Reply Last reply
                          0
                          • M Mark Salsbery

                            Heh no problem. I work alone at home - I don't get to have these water-cooler discussions with colleagues :) Cheers!

                            Mark Salsbery Microsoft MVP - Visual C++ :java:

                            J Offline
                            J Offline
                            Jammer 0
                            wrote on last edited by
                            #13

                            heh ... they can be really beneficial! Although I'm still at a stage in learning .NET where I come away with more questions than answers! Doh!

                            Jammer My Blog | Article(s)

                            1 Reply Last reply
                            0
                            • J Jammer 0

                              Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

                              Jammer My Blog | Article(s)

                              C Offline
                              C Offline
                              carbon_golem
                              wrote on last edited by
                              #14

                              Not to beat the "dead horse" here, but I didn't see anyone bring up the induced complexity that the switch adds. See complexity definition here.[^] The higher the complexity score, the more trouble maintenance and testing become. The switch is very efficient at adding additional paths in the code (cases - 1). While yes, the readability is there, one could argue at the same time a certain amount of flexibility is lost at the expense. There are more or less feasible ways around using a switch or bank of if/else altogether - using the chain-of-responsibility pattern has worked for me in some situations. And certainly it has made unit testing easier. I might correct your colleague's statement and submit that maybe the architecture isn't "wrong" by using a switch, it just might be pointing out that there are higher quality alternatives. Scott P.

                              "Simplicity carried to the extreme becomes elegance."
                              -Jon Franklin

                              L realJSOPR 2 Replies Last reply
                              0
                              • J Jammer 0

                                Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

                                Jammer My Blog | Article(s)

                                L Offline
                                L Offline
                                led mike
                                wrote on last edited by
                                #15

                                Jammer wrote:

                                What do other folks think of this?

                                It's not Object Oriented and the following is a section of my own notes to myself (quotes ) from Kent Becks book "Implementation Patterns"Conditional (page 36)

                                If/then and switch statements are the simplest form of
                                instance –specific behavior….

                                The more paths through a program the less likely the program
                                is to be correct….The proliferation of conditionals reduces reliability….This
                                problem is compounded when conditionals are duplicated.

                                These problems can all be eliminated by converting the
                                conditional logic to messages, either with subclasses or delegation.


                                Last modified: 5hrs 28mins after originally posted --

                                led mike

                                M 1 Reply Last reply
                                0
                                • C carbon_golem

                                  Not to beat the "dead horse" here, but I didn't see anyone bring up the induced complexity that the switch adds. See complexity definition here.[^] The higher the complexity score, the more trouble maintenance and testing become. The switch is very efficient at adding additional paths in the code (cases - 1). While yes, the readability is there, one could argue at the same time a certain amount of flexibility is lost at the expense. There are more or less feasible ways around using a switch or bank of if/else altogether - using the chain-of-responsibility pattern has worked for me in some situations. And certainly it has made unit testing easier. I might correct your colleague's statement and submit that maybe the architecture isn't "wrong" by using a switch, it just might be pointing out that there are higher quality alternatives. Scott P.

                                  "Simplicity carried to the extreme becomes elegance."
                                  -Jon Franklin

                                  L Offline
                                  L Offline
                                  led mike
                                  wrote on last edited by
                                  #16

                                  carbon_golem wrote:

                                  there are higher quality alternatives.

                                  Agreed. See my post below, that you just beat to the wire! Damn you! :laugh:

                                  led mike

                                  1 Reply Last reply
                                  0
                                  • J Jammer 0

                                    Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

                                    Jammer My Blog | Article(s)

                                    realJSOPR Offline
                                    realJSOPR Offline
                                    realJSOP
                                    wrote on last edited by
                                    #17

                                    Well, your colleague is a moron, and it sound s like his father should have used a switch on him more often when he was a child.

                                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                    -----
                                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                    J 1 Reply Last reply
                                    0
                                    • C carbon_golem

                                      Not to beat the "dead horse" here, but I didn't see anyone bring up the induced complexity that the switch adds. See complexity definition here.[^] The higher the complexity score, the more trouble maintenance and testing become. The switch is very efficient at adding additional paths in the code (cases - 1). While yes, the readability is there, one could argue at the same time a certain amount of flexibility is lost at the expense. There are more or less feasible ways around using a switch or bank of if/else altogether - using the chain-of-responsibility pattern has worked for me in some situations. And certainly it has made unit testing easier. I might correct your colleague's statement and submit that maybe the architecture isn't "wrong" by using a switch, it just might be pointing out that there are higher quality alternatives. Scott P.

                                      "Simplicity carried to the extreme becomes elegance."
                                      -Jon Franklin

                                      realJSOPR Offline
                                      realJSOPR Offline
                                      realJSOP
                                      wrote on last edited by
                                      #18

                                      carbon_golem wrote:

                                      it just might be pointing out that there are higher quality alternatives.

                                      You mean like "goto"? LOLOL

                                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                      -----
                                      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                      1 Reply Last reply
                                      0
                                      • realJSOPR realJSOP

                                        Well, your colleague is a moron, and it sound s like his father should have used a switch on him more often when he was a child.

                                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                        -----
                                        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                        J Offline
                                        J Offline
                                        Jammer 0
                                        wrote on last edited by
                                        #19

                                        Whoa ... it wasn't my colleague that stated this ... he was passing on things he'd read/heard ... it was a light-hearted conversation! He is far from a Moron as well, a very good developer in fact.

                                        Jammer My Blog | Article(s)

                                        1 Reply Last reply
                                        0
                                        • J Jammer 0

                                          Hi All, I was recently talking to a colleague at work and the topic came round to using swith(). He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere. What do other folks think of this? Cheers,

                                          Jammer My Blog | Article(s)

                                          G Offline
                                          G Offline
                                          Guffa
                                          wrote on last edited by
                                          #20

                                          Jammer wrote:

                                          He said that he'd read/heard more than once that if you find yourself using a switch you can more or less be assured that its because you've done something wrong in your architecture elsewhere.

                                          That probably comes from someone who don't know how to use a switch properly... What seems more elegant? This:

                                          int result;
                                          SomeClass.SomeEnum value = SomeClass.GetValue();
                                          if (value == SomeClass.SomeEnum.Option1 || value == SomeClass.SomeEnum.Option2) {
                                          result = 1;
                                          } else if (value == SomeClass.SomeEnum.Option3) {
                                          result = 2;
                                          } else if (value == SomeClass.SomeEnum.Option4 || value == SomeClass.SomeEnum.Option5 || value == SomeClass.SomeEnum.Option6) {
                                          result = 3;
                                          } else {
                                          result = 4;
                                          }

                                          or this:

                                          int result;
                                          switch (SomeClass.GetValue()) {
                                          case SomeClass.SomeEnum.Option1:
                                          case SomeClass.SomeEnum.Option2: result = 1; break;
                                          case SomeClass.SomeEnum.Option3: result = 2; break;
                                          case SomeClass.SomeEnum.Option4:
                                          case SomeClass.SomeEnum.Option5:
                                          case SomeClass.SomeEnum.Option6: result = 3; break;
                                          default: result = 4; break;
                                          }

                                          Besides, the switch solution is faster.

                                          Despite everything, the person most likely to be fooling you next is yourself.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups