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 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
          • P PIEBALDconsult

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

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

            Actually, if you have more than just a few case labels in a switch (four IIRC), it's implemented using a dictionary.

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

            P 1 Reply Last reply
            0
            • L led mike

              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 Offline
              M Offline
              Mark Salsbery
              wrote on last edited by
              #22

              :omg:

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

              L 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
                Colin Angus Mackay
                wrote on last edited by
                #23

                It depends on the situation. There are definitely situations where I've seen needless use of switch statements, and others that would have benefitted from a switch statement. If you find that you are switching on a specific property of a class a lot within that class then it can be an indication that you might want to refactor the code into a class hierarchy. Each derived class handles a specific case that was in the switch statement.

                Recent blog posts: *Method hiding Vs. overriding *Microsoft Surface *SQL Server / Visual Studio install order My Blog

                1 Reply Last reply
                0
                • M Mark Salsbery

                  :omg:

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

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

                  Wow what a mess. Fixed. Thanks

                  1 Reply Last reply
                  0
                  • G Guffa

                    Actually, if you have more than just a few case labels in a switch (four IIRC), it's implemented using a dictionary.

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

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

                    Yeah, more than five, as you showed back in July. I keep forgetting that. On the other hand, using your own Dictionary gives you more flexibility and the ability to use it in multiple places (if you can think of such a use).

                    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)

                      N Offline
                      N Offline
                      N a v a n e e t h
                      wrote on last edited by
                      #26

                      As others said, switch statement has many benefits. So use it wisely. You should read something about method cohesion[^].

                      Navaneeth How to use google | Ask smart questions

                      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:

                        V Offline
                        V Offline
                        Vengatachalapathy Palanivel
                        wrote on last edited by
                        #27

                        Switch case is better in performance than if-else-if ladder. While using switch case, compiler optimizes the code for the fastest execution. you can check this Url also: http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx[^]

                        Regards, Vengat P

                        M 1 Reply Last reply
                        0
                        • V Vengatachalapathy Palanivel

                          Switch case is better in performance than if-else-if ladder. While using switch case, compiler optimizes the code for the fastest execution. you can check this Url also: http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx[^]

                          Regards, Vengat P

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

                          That was my point[^]

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

                          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
                            Jakob Olsen
                            wrote on last edited by
                            #29

                            Pete O'Hanlon wrote:

                            It's like everything else in C# - use it when you have to.

                            Couldn't agree more. I have heard the "using construct X is really bad design" about more or less every construct in C/C++/C#, but they all have situations where they are just right, so use them where they make sense. (yes... even "goto"...)

                            ASCII tables, HTML entities, types, string formats and more info for the serious coder at: www.codecharts.com

                            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