Results 1 to 24 of 24

Thread: Select case versus If statement

  1. #1

    Thread Starter
    Hyperactive Member gonzalioz's Avatar
    Join Date
    Sep 2009
    Location
    <body></body>
    Posts
    508

    Select case versus If statement

    Hi all,

    I am not really a fan of if statements. I think they should only be used when comparing different values like this:

    Code:
    Dim status as boolean = false
    Dim number as integer = 5
    
    if status.equals(true) then
    
    elseif number = 5 then
    
    else
    
    end if

    However, people say that if should also be used if you don't have more then 2 options.

    For example:
    Code:
    Dim status as boolean = false
    
    if status.equals(true) then
    msgbox("true")
    else
    msgbox("false")
    end if
    I would rather use:

    Code:
    Select case status
    case true: msgbox("true")
    case else: msgbox("false")
    
    or msgbox on a different line whatever you want....
    What is this rule about that select case should only be used if there more then 2-3 options. Is it wrong to use a select case instead?

  2. #2
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,127

    Re: Select case versus If statement

    It may boil down to one's preference, with many conditions SELECT CASE tends to be more readable (to me) and in cases of two conditions then IF ELSE is fine.
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  3. #3
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Select case versus If statement

    I tend to use Select Case a lot when it comes to this stuff, but when it's only two items and if the first condition is false, the second condition is assumed to be true then I'll use an
    If Then
    Else
    End If

    structure
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  4. #4
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: Select case versus If statement

    In my opinion, using If/Else is much more intuitive. You can read it almost as normal english:
    Code:
    If (some condition is true) Then
       do this
    Else
       do that
    End If
    The same cannot be said for select case as easily:
    Code:
    Select Case (some condition)
       Case True
          do this
       Case False
          do that
    End Select
    It's just personal preference though... I wouldn't be surprised even if it compiles to the same code in the end (but it probably doens't).

  5. #5
    Frenzied Member ntg's Avatar
    Join Date
    Sep 2004
    Posts
    1,449

    Re: Select case versus If statement

    To find a performance difference between two If statements and the corresponding Select statement, you'd probably need to use a multimedia timer or perform both operations several million times in a row. The difference in performance is negligible so I would say it is a matter of personal preference.

    Having said that, there really is a difference between If and Select. The Select statement is normally translated to the switch IL instruction which is very efficient. So for the code:
    VB Code:
    1. Public Enum testEnum
    2.     enum1 = 0
    3.     enum2
    4.     enum3
    5. End Enum
    6.  
    7. Public Sub test()
    8.     Dim s As testEnum = testEnum.enum1
    9.     Select Case s
    10.         Case testEnum.enum1
    11.             s = testEnum.enum2
    12.         Case testEnum.enum2
    13.             s = testEnum.enum3
    14.         Case testEnum.enum3
    15.             s = testEnum.enum1
    16.     End Select
    17. End Sub
    the IL for sub test() is:
    Code:
    .method public static void  test() cil managed
    {
      // Code size       33 (0x21)
      .maxstack  1
      .locals init ([0] valuetype recursor.Module1/testEnum s,
               [1] valuetype recursor.Module1/testEnum VB$t_i4$L0)
      IL_0000:  ldc.i4.0
      IL_0001:  stloc.0
      IL_0002:  ldloc.0
      IL_0003:  switch     ( 
                            IL_0016,
                            IL_001a,
                            IL_001e)
      IL_0014:  br.s       IL_0020
      IL_0016:  ldc.i4.1
      IL_0017:  stloc.0
      IL_0018:  br.s       IL_0020
      IL_001a:  ldc.i4.2
      IL_001b:  stloc.0
      IL_001c:  br.s       IL_0020
      IL_001e:  ldc.i4.0
      IL_001f:  stloc.0
      IL_0020:  ret
    } // end of method Module1::test
    However, if you use an expression which is not a boolean or an enumeration, the compiler will generate a series of If statements that will be exactly the same as you were coding a series of If statements yourself. Likewise, if you arbitrarily change the values of your enumerations, the switch statement will be altered. So for the code:
    VB Code:
    1. Public Enum testEnum
    2.     enum1 = 0
    3.     enum2 = 2   '<<< Specifically assign value.
    4.     enum3 = 5   '<<< Specifically assign value.
    5. End Enum
    6.  
    7. Public Sub test()
    8.     Dim s As testEnum = testEnum.enum1
    9.     Select Case s
    10.         Case testEnum.enum1
    11.             s = testEnum.enum2
    12.         Case testEnum.enum2
    13.             s = testEnum.enum3
    14.         Case testEnum.enum3
    15.             s = testEnum.enum1
    16.     End Select
    17. End Sub
    the following IL is generated:
    Code:
    .method public static void  test() cil managed
    {
      // Code size       45 (0x2d)
      .maxstack  1
      .locals init ([0] valuetype recursor.Module1/testEnum s,
               [1] valuetype recursor.Module1/testEnum VB$t_i4$L0)
      IL_0000:  ldc.i4.0
      IL_0001:  stloc.0
      IL_0002:  ldloc.0
      IL_0003:  switch     ( 
                            IL_0022,
                            IL_002c,
                            IL_0026,
                            IL_002c,
                            IL_002c,
                            IL_002a)
      IL_0020:  br.s       IL_002c
      IL_0022:  ldc.i4.2
      IL_0023:  stloc.0
      IL_0024:  br.s       IL_002c
      IL_0026:  ldc.i4.5
      IL_0027:  stloc.0
      IL_0028:  br.s       IL_002c
      IL_002a:  ldc.i4.0
      IL_002b:  stloc.0
      IL_002c:  ret
    } // end of method Module1::test
    Note that the switch statement switches for six cases because the compiler knows that the enumeration starts at 0 and ends at 5.
    "Feel the force...read the source..."
    Utilities: POPFileDebugViewProcess ExplorerWiresharkKeePassUltraVNCPic2Ascii
    .Net tools & open source: DotNetNukelog4NetCLRProfiler
    My open source projects: Thales SimulatorEFT CalculatorSystem Info ReporterVSS2SVNIBAN Functions
    Customer quote: "If the server has a RAID array, why should we bother with backups?"
    Programmer quote: "I never comment my code. Something that is hard to write should be impossible to comprehend."
    Ignorant quote: "I have no respect for universities, as they teach not practicle stuff, and charge money for"

  6. #6
    Pro Grammar chris128's Avatar
    Join Date
    Jun 2007
    Location
    England
    Posts
    7,604

    Re: Select case versus If statement

    In my opinion, using If/Else is much more intuitive. You can read it almost as normal english
    Same here, I find Select Case statements horrible to look at and read for some reason..
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


  7. #7
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Select case versus If statement

    I like using Select Case like this when I want specific conditions.
    vb Code:
    1. Select Case True
    2. Case j = 5 AndAlso i = 6
    3. 'code...
    4. Case j = 6 AndAlso i = 5
    5. End Select
    Especially with long AndAlso lines, it can be very hard to read when using If.

  8. #8
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: Select case versus If statement

    I tend to use Select Case in this situation:
    Code:
            Select Case x
                Case 0 To 5, 9, 12 To 20
    
                Case Else
    
            End Select
    Using If, that would be very hard to read
    Code:
            If (x >= 0 AndAlso x <= 5) OrElse x = 9 OrElse (x >= 12 AndAlso x <= 20) Then
    
            Else
    
            End If
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  9. #9
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Select case versus If statement

    Hey,

    As has already been mentioned, it comes down to personal preference.

    If I have two conditions, i.e. true or false, then to me, this is a natural fit for If/Else. However, if there are a number of conditions that need to be checked, then I would default to a Select Statement.

    Gary

  10. #10
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Select case versus If statement

    I usually prefer one liners where ever possible. I feel it easier to maintain it that way as I have lesser code to deal with. Don't know about performance implications though.

    So Instead of this:
    Code:
    Dim status as boolean = false
    
    if status.equals(true) then
    msgbox("true")
    else
    msgbox("false")
    end if
    or this:
    Code:
    Select case status
    case true: msgbox("true")
    case else: msgbox("false")
    
    or msgbox on a different line whatever you want....
    I would prefer:

    vb.net Code:
    1. MsgBox(If(Status, "True", "False"))
    2. 'or
    3. If Status Then MsgBox("True") Else MsgBox("False")
    4. 'etc.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  11. #11
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Select case versus If statement

    Quote Originally Posted by Pradeep1210 View Post
    I usually prefer one liners where ever possible. I feel it easier to maintain it that way as I have lesser code to deal with. Don't know about performance implications though.

    So Instead of this:
    Code:
    Dim status as boolean = false
    
    if status.equals(true) then
    msgbox("true")
    else
    msgbox("false")
    end if
    or this:
    Code:
    Select case status
    case true: msgbox("true")
    case else: msgbox("false")
    
    or msgbox on a different line whatever you want....
    I would prefer:

    vb.net Code:
    1. MsgBox(If(Status, "True", "False"))
    2. 'or
    3. If Status Then MsgBox("True") Else MsgBox("False")
    4. 'etc.
    Why not:
    Code:
    Messagebox.Show(Status.ToString)
    ?
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  12. #12
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Select case versus If statement

    Hey,

    In fairness to Pradeep, I think he was just trying to give a simple example of the technique that he uses.

    Gary

  13. #13
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Select case versus If statement

    Quote Originally Posted by JuggaloBrotha View Post
    Why not:
    Code:
    Messagebox.Show(Status.ToString)
    ?
    Yes, that too is ok as long as we need to show "True" and "False" only in the messagebox. I was just trying to get the equivalent of OP's code.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  14. #14
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Select case versus If statement

    Quote Originally Posted by gep13 View Post
    Hey,

    In fairness to Pradeep, I think he was just trying to give a simple example of the technique that he uses.

    Gary
    Yes exactly
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  15. #15
    Stack Overflow mod​erator
    Join Date
    May 2008
    Location
    British Columbia, Canada
    Posts
    2,824

    Re: Select case versus If statement

    If() new in VS 2010 or something?

  16. #16
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Select case versus If statement

    Quote Originally Posted by minitech View Post
    If() new in VS 2010 or something?
    VS 2008 actually
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  17. #17
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Select case versus If statement

    Quote Originally Posted by minitech View Post
    If() new in VS 2010 or something?
    Yes.

    Then new If() operator behaves like the short-circuited If operators (actually it is ?: in other languages). It evaluates only that part that is required.
    VB was lacking this single If() operator that other languages have.
    VB already had IIf() function. But it evaluates both the true as well as false conditions. So it was slower (as well as unfit for some cases) than the new If() operator
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  18. #18

    Thread Starter
    Hyperactive Member gonzalioz's Avatar
    Join Date
    Sep 2009
    Location
    <body></body>
    Posts
    508

    Re: Select case versus If statement

    Quote Originally Posted by Pradeep1210 View Post
    I would prefer:

    vb.net Code:
    1. MsgBox(If(Status, "True", "False"))
    2. 'or
    3. If Status Then MsgBox("True") Else MsgBox("False")
    4. 'etc.
    @Pradeep

    A bit off topic but.. How do you make your code colored?

  19. #19
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Select case versus If statement

    Hey,

    I believe I am correct in saying that this is done using VBCODE tags, rather than standard CODE tags:

    Code:
    MsgBox(If(Status, "True", "False"))
    'or
    If Status Then MsgBox("True") Else MsgBox("False")
    'etc.
    vb.net Code:
    1. MsgBox(If(Status, "True", "False"))
    2. 'or
    3. If Status Then MsgBox("True") Else MsgBox("False")
    4. 'etc.

    VBCODE tags, actually render a HIGHLIGHT tag, which you can provide an argument to, i.e. HIGHLIGHT=vb, or HIGHLIGHT=vb.net

    Gary

  20. #20
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Select case versus If statement

    Yep. either select your code and click the VBCode button on the toolbar, that will automatically put the tags for you.
    Or you may manually put your code between [HIGHLIGHT=vb.net] [/HIGHLIGHT] tags.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  21. #21
    Hyperactive Member doctrin13th's Avatar
    Join Date
    Sep 2008
    Posts
    303

    Re: Select case versus If statement

    Quote Originally Posted by minitech View Post
    I like using Select Case like this when I want specific conditions.
    vb Code:
    1. Select Case True
    2. Case j = 5 AndAlso i = 6
    3. 'code...
    4. Case j = 6 AndAlso i = 5
    5. End Select
    Especially with long AndAlso lines, it can be very hard to read when using If.
    What is the difference in using Case j=5 And i=6 with Case j=5 AndAlso i=6?

    Quote Originally Posted by stanav View Post
    I tend to use Select Case in this situation:
    Code:
            Select Case x
                Case 0 To 5, 9, 12 To 20
    
                Case Else
    
            End Select
    Using If, that would be very hard to read
    Code:
            If (x >= 0 AndAlso x <= 5) OrElse x = 9 OrElse (x >= 12 AndAlso x <= 20) Then
    
            Else
    
            End If
    Also here, what is the difference between And and AndAlso, and OR and OrElse?

    Confused...

  22. #22
    Freelancer akhileshbc's Avatar
    Join Date
    Jun 2008
    Location
    Trivandrum, Kerala, India
    Posts
    7,652

    Re: Select case versus If statement

    Quote Originally Posted by doctrin13th View Post
    What is the difference in using Case j=5 And i=6 with Case j=5 AndAlso i=6?



    Also here, what is the difference between And and AndAlso, and OR and OrElse?

    Confused...
    Check this: http://social.msdn.microsoft.com/for...a-3815db83e2b3 ....

    If my post was helpful to you, then express your gratitude using Rate this Post.
    And if your problem is SOLVED, then please Mark the Thread as RESOLVED (see it in action - video)
    My system: AMD FX 6100, Gigabyte Motherboard, 8 GB Crossair Vengance, Cooler Master 450W Thunder PSU, 1.4 TB HDD, 18.5" TFT(Wide), Antec V1 Cabinet

    Social Group: VBForums - Developers from India


    Skills: PHP, MySQL, jQuery, VB.Net, Photoshop, CodeIgniter, Bootstrap,...

  23. #23
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: Select case versus If statement

    There is some more discussion on this here:

    http://visualbasic.about.com/od/quic...vbnetlogop.htm

    As well as the MSDN documentation here:

    And
    AndAlso
    Or
    OrElse

    Gary

  24. #24
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Select case versus If statement

    Also, about performance.
    Even though the difference is minimal, the code will be faster if you provide the expression which is more likely to appear first. For example (applies to both If and Select Case):

    Code:
    If moreprobablecondition Then
       ...
    Else
       ...
    End If
    Or

    Code:
    Select Case expression
         Case moreprobablevalue ' Should come first
         Case Else
    End Select

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width