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
  1. Home
  2. General Programming
  3. C#
  4. A matter of style : Switch or ?: [modified]

A matter of style : Switch or ?: [modified]

Scheduled Pinned Locked Moved C#
javascriptperformancequestion
16 Posts 12 Posters 0 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.
  • M Offline
    M Offline
    mgkr
    wrote on last edited by
    #1

    Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

    int i;

    switch (ID) {
    case "a":
    i = 1;
    break;
    case "b":
    i= 2;
    break;
    case "c":
    i = 3;
    break;
    default:
    i = 0;
    break;
    }

    B:

    int i;

    i = ID == "a" ? 1 :
    ID == "b" ? 2 :
    ID == "c" ? 3 :
    0;

    What would you use (and why)?

    modified on Tuesday, October 20, 2009 6:46 AM

    OriginalGriffO C S P J 12 Replies Last reply
    0
    • M mgkr

      Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

      int i;

      switch (ID) {
      case "a":
      i = 1;
      break;
      case "b":
      i= 2;
      break;
      case "c":
      i = 3;
      break;
      default:
      i = 0;
      break;
      }

      B:

      int i;

      i = ID == "a" ? 1 :
      ID == "b" ? 2 :
      ID == "c" ? 3 :
      0;

      What would you use (and why)?

      modified on Tuesday, October 20, 2009 6:46 AM

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      Under normal circumstances I would go for the switch - but as it wouldn't work

      case "b":
      i= 2;
      break;
      case "b":
      i = 3;
      break;

      I would have to fix it first! The second is horrible - clarity and readability are much more important than saving space on screen.

      No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      1 Reply Last reply
      0
      • M mgkr

        Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

        int i;

        switch (ID) {
        case "a":
        i = 1;
        break;
        case "b":
        i= 2;
        break;
        case "c":
        i = 3;
        break;
        default:
        i = 0;
        break;
        }

        B:

        int i;

        i = ID == "a" ? 1 :
        ID == "b" ? 2 :
        ID == "c" ? 3 :
        0;

        What would you use (and why)?

        modified on Tuesday, October 20, 2009 6:46 AM

        C Offline
        C Offline
        Christian Graus
        wrote on last edited by
        #3

        The switch, because it's readable and maintainable.

        Christian Graus Driven to the arms of OSX by Vista. Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.

        1 Reply Last reply
        0
        • M mgkr

          Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

          int i;

          switch (ID) {
          case "a":
          i = 1;
          break;
          case "b":
          i= 2;
          break;
          case "c":
          i = 3;
          break;
          default:
          i = 0;
          break;
          }

          B:

          int i;

          i = ID == "a" ? 1 :
          ID == "b" ? 2 :
          ID == "c" ? 3 :
          0;

          What would you use (and why)?

          modified on Tuesday, October 20, 2009 6:46 AM

          S Offline
          S Offline
          Simon P Stevens
          wrote on last edited by
          #4

          I agree with OriginalGriff. I'd use switch every time. The conditional operator is fine for small in line statements, but nesting it like that just makes it unreadable too quickly. The switch is much more readable.

          Simon

          1 Reply Last reply
          0
          • M mgkr

            Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

            int i;

            switch (ID) {
            case "a":
            i = 1;
            break;
            case "b":
            i= 2;
            break;
            case "c":
            i = 3;
            break;
            default:
            i = 0;
            break;
            }

            B:

            int i;

            i = ID == "a" ? 1 :
            ID == "b" ? 2 :
            ID == "c" ? 3 :
            0;

            What would you use (and why)?

            modified on Tuesday, October 20, 2009 6:46 AM

            J Offline
            J Offline
            Jacobb Michael
            wrote on last edited by
            #5

            Hi, if it is just one matching you can go with approach 'B' otherwise i will prefer the First Approach 'A' because the Second Type has to be parsed as first and process. and Even if it is more than 2 matching it is not good practice to use 'B' because it is not much readable and understandable.and for each case we can make a comment(purpose) in 'A', But it is not suitable for 'B' but anyway it depends on the place where use, and the situation where you use,and even the appearance where you use thanks

            1 Reply Last reply
            0
            • M mgkr

              Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

              int i;

              switch (ID) {
              case "a":
              i = 1;
              break;
              case "b":
              i= 2;
              break;
              case "c":
              i = 3;
              break;
              default:
              i = 0;
              break;
              }

              B:

              int i;

              i = ID == "a" ? 1 :
              ID == "b" ? 2 :
              ID == "c" ? 3 :
              0;

              What would you use (and why)?

              modified on Tuesday, October 20, 2009 6:46 AM

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

              It depends on the complexity of the case. I'd definitely avoid the second condition because debugging nested ternary's is an absolute nightmare. In a more complex case than this though, I'd drop both constructs in favour of an Action or Func. Have a look at the Log class in my article here[^] to see how it works. The basic approach is to set up a set of Actions (or Funcs) that correspond to the operations in your switch statement and assign them to a dictionary (the key in the dictionary is the value for your switch statement). All you need do then is trigger the appropriate action based on the key. In the log sample, this line actually performs the validation:

              _actions[level](message);

              "WPF has many lovers. It's a veritable porn star!" - Josh Smith

              As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

              My blog | My articles | MoXAML PowerToys | Onyx

              1 Reply Last reply
              0
              • M mgkr

                Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                int i;

                switch (ID) {
                case "a":
                i = 1;
                break;
                case "b":
                i= 2;
                break;
                case "c":
                i = 3;
                break;
                default:
                i = 0;
                break;
                }

                B:

                int i;

                i = ID == "a" ? 1 :
                ID == "b" ? 2 :
                ID == "c" ? 3 :
                0;

                What would you use (and why)?

                modified on Tuesday, October 20, 2009 6:46 AM

                N Offline
                N Offline
                nagendrathecoder
                wrote on last edited by
                #7

                I'll go for Switch because its easy to track errors in that.

                1 Reply Last reply
                0
                • M mgkr

                  Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                  int i;

                  switch (ID) {
                  case "a":
                  i = 1;
                  break;
                  case "b":
                  i= 2;
                  break;
                  case "c":
                  i = 3;
                  break;
                  default:
                  i = 0;
                  break;
                  }

                  B:

                  int i;

                  i = ID == "a" ? 1 :
                  ID == "b" ? 2 :
                  ID == "c" ? 3 :
                  0;

                  What would you use (and why)?

                  modified on Tuesday, October 20, 2009 6:46 AM

                  M Offline
                  M Offline
                  mgkr
                  wrote on last edited by
                  #8

                  @OriginalGriff Fixed the switch for ya ;P clarity and readability are much more important than saving space on screen. Agreed 100% Which is why I posted - As the ?: was/is very clear to me, and I can at a glance understand what's going on, but I'm well aware it's not a construct used that/as often, so wanted to test the waters with other coders. -debugging nested ternary's is an absolute nightmare -I'll go for Switch because its easy to track errors in that. Good point As this is a *very* simple case I didn't even think of that actually. But it might need to get more complicated as the code evolves. Where I'm using it, it's not very likely though - But those are "famous last words", so point taken and agreed to. -- Thank you all for the feed back - I'll tidy up my code now :cool:

                  1 Reply Last reply
                  0
                  • M mgkr

                    Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                    int i;

                    switch (ID) {
                    case "a":
                    i = 1;
                    break;
                    case "b":
                    i= 2;
                    break;
                    case "c":
                    i = 3;
                    break;
                    default:
                    i = 0;
                    break;
                    }

                    B:

                    int i;

                    i = ID == "a" ? 1 :
                    ID == "b" ? 2 :
                    ID == "c" ? 3 :
                    0;

                    What would you use (and why)?

                    modified on Tuesday, October 20, 2009 6:46 AM

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

                    As others said switch is more readable in this case. Also when switch has more labels, compilers use a lookup table (probably hash tables) to implement that and it will yield in accessing all the labels in constant time. :)

                    Best wishes, Navaneeth

                    1 Reply Last reply
                    0
                    • M mgkr

                      Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                      int i;

                      switch (ID) {
                      case "a":
                      i = 1;
                      break;
                      case "b":
                      i= 2;
                      break;
                      case "c":
                      i = 3;
                      break;
                      default:
                      i = 0;
                      break;
                      }

                      B:

                      int i;

                      i = ID == "a" ? 1 :
                      ID == "b" ? 2 :
                      ID == "c" ? 3 :
                      0;

                      What would you use (and why)?

                      modified on Tuesday, October 20, 2009 6:46 AM

                      K Offline
                      K Offline
                      Keith Barrow
                      wrote on last edited by
                      #10

                      The swtich statement is more readable here, but I think in general swtiches give of a bad code smell:clickety[^] Especially if they are large or used repeatedly.

                      CCC solved so far: 2 (including a Hard One!)

                      P 1 Reply Last reply
                      0
                      • M mgkr

                        Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                        int i;

                        switch (ID) {
                        case "a":
                        i = 1;
                        break;
                        case "b":
                        i= 2;
                        break;
                        case "c":
                        i = 3;
                        break;
                        default:
                        i = 0;
                        break;
                        }

                        B:

                        int i;

                        i = ID == "a" ? 1 :
                        ID == "b" ? 2 :
                        ID == "c" ? 3 :
                        0;

                        What would you use (and why)?

                        modified on Tuesday, October 20, 2009 6:46 AM

                        N Offline
                        N Offline
                        Nisha Agrawal
                        wrote on last edited by
                        #11

                        It's not the matter of readability, infact i'll use switch due to performance gain over multiple if-else statements. There is detailed description of this thought here. http://www.ozcandegirmenci.com/post/2008/05/Switch-vs-If.aspx[^]

                        P 1 Reply Last reply
                        0
                        • M mgkr

                          Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                          int i;

                          switch (ID) {
                          case "a":
                          i = 1;
                          break;
                          case "b":
                          i= 2;
                          break;
                          case "c":
                          i = 3;
                          break;
                          default:
                          i = 0;
                          break;
                          }

                          B:

                          int i;

                          i = ID == "a" ? 1 :
                          ID == "b" ? 2 :
                          ID == "c" ? 3 :
                          0;

                          What would you use (and why)?

                          modified on Tuesday, October 20, 2009 6:46 AM

                          L Offline
                          L Offline
                          Luc Pattyn
                          wrote on last edited by
                          #12

                          mgkr wrote:

                          What would you use (and why)?

                          neither, because 1) needing such a conversion often indicates a bad design e.g. a bad choice of data structuring; 2) and when unavoidable, i.e. when I do need to map characters to small positive integers, I use a snippet that is based on "literalString".IndexOf(char) PS: at least two replies mentioned readability, which does not even appear (any more?) in the OP. I hate it when the OP gets edited, and yes readability is very important. :)

                          Luc Pattyn


                          I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


                          Local announcement (Antwerp region): Lange Wapper? 59.24% waren verstandig genoeg om NEEN te stemmen; bye bye viaduct.


                          P 1 Reply Last reply
                          0
                          • L Luc Pattyn

                            mgkr wrote:

                            What would you use (and why)?

                            neither, because 1) needing such a conversion often indicates a bad design e.g. a bad choice of data structuring; 2) and when unavoidable, i.e. when I do need to map characters to small positive integers, I use a snippet that is based on "literalString".IndexOf(char) PS: at least two replies mentioned readability, which does not even appear (any more?) in the OP. I hate it when the OP gets edited, and yes readability is very important. :)

                            Luc Pattyn


                            I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


                            Local announcement (Antwerp region): Lange Wapper? 59.24% waren verstandig genoeg om NEEN te stemmen; bye bye viaduct.


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

                            10!

                            1 Reply Last reply
                            0
                            • M mgkr

                              Suddenly not sure which of the following constructs I should go with... I really like the compactness of B, but a bit unsure how my fellow coders would react to seeing the construct. I can't see how there should be any performance differences (if you know differently - Do tell) A:

                              int i;

                              switch (ID) {
                              case "a":
                              i = 1;
                              break;
                              case "b":
                              i= 2;
                              break;
                              case "c":
                              i = 3;
                              break;
                              default:
                              i = 0;
                              break;
                              }

                              B:

                              int i;

                              i = ID == "a" ? 1 :
                              ID == "b" ? 2 :
                              ID == "c" ? 3 :
                              0;

                              What would you use (and why)?

                              modified on Tuesday, October 20, 2009 6:46 AM

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

                              Neither.

                              public enum IDenum { None , a , b , c }

                              ...

                              IDenum ID = System.Enum.Parse ( typeof(IDenum) , whatever ) ;

                              (Except I use my own TryParse method.)

                              1 Reply Last reply
                              0
                              • N Nisha Agrawal

                                It's not the matter of readability, infact i'll use switch due to performance gain over multiple if-else statements. There is detailed description of this thought here. http://www.ozcandegirmenci.com/post/2008/05/Switch-vs-If.aspx[^]

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

                                No, it's definitely about readability.

                                1 Reply Last reply
                                0
                                • K Keith Barrow

                                  The swtich statement is more readable here, but I think in general swtiches give of a bad code smell:clickety[^] Especially if they are large or used repeatedly.

                                  CCC solved so far: 2 (including a Hard One!)

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

                                  In my opinion, a switch on a string value is definitely a code smell. But using if/else or the ternary operator simply to avoid a switch is worse.

                                  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