Our full technical support staff does not monitor this forum. If you need assistance from a member of our staff, please submit your question from the Ask a Question page.


Log in or register to post/reply in the forum.

Select-Case versus If-Then statements


pokeeffe Apr 14, 2017 08:05 PM

General curiousity question here. I've seen Select-Case statements used where an If-Then would make as much or more sense. For example:

    Select Case Td_gu_probe
    Case Is >= 0
      Td_probe = 238.88*x_tmp_probe/(17.368 - x_tmp_probe)
    Case Is < 0
      Td_probe = 247.15*x_tmp_probe/(17.966 - x_tmp_probe)
    EndSelect

Are there practical reasons to prefer one idiom over the other?


GTProdMgr Apr 14, 2017 08:35 PM

"Select Case" blocks and "If-Then" blocks are both conditional processing structures. The general rule is to consider readability and understanding when coming back to look at the code later. The typical decision would be to go with a Select-Case block if you are choosing between 3 or more options (relating to the single Case variable). If there are only 2 options, then an "If-Then" block keeps it simpler (more like English). It is theoretically possible to perform an identical operation for a given Select-Case block using multiple "If-Then" statements instead, it just gets "ugly/complex". The hope is for "clean" looking code (readability). You can also use "If- Else If- Else" to handle cases with 3 options, so the rule of "3 options" isn't hard and fast, but just in the general ball park. Since there are multiple ways of accomplishing the same thing, there is a bit of an "art" to this.

When you encounter a choice between 20 options and it is implemented as "Select-Case", you are grateful that the program writer opted on the side of readability.

It is possible that the program writer in your case anticipated more cases than two at some point in the future. Or the code could have been generated (i.e. Shortcut) in which case generalized algorithms are used that are indepdendent of the number of options (i.e., number of options not known in advance).

Log in or register to post/reply in the forum.