ISCL is a Intelligent Information Consulting System. Based on our knowledgebase, using AI tools such as CHATGPT, Customers could customize the information according to their needs, So as to achieve

When is If Then Else better than Select Case?

1


Select Case and If-Then-Else can be used for exactly the same programming problems. It's up to you, as a programmer, to decide which one works best. Let's look at some code (used in a popular Microsoft Step by Step text from years past - the numbers are a little dated now).

If-Then-Else


Dim AdjustedIncome, TaxDue As DoubleIf AdjustedIncome
Whenever you have a series of decisions like this, a Select Case structure can also be used.


Here's the same code using a Select Case Structure.

Select Case Structure


Select Case AdjustedIncomeCase Is
If you initialize AdjustedIncome to say, $1,000,000 (that is, a small, insignificant fraction of what Bill Gates makes in a year), you will find that you get exactly the same answer with either code.

So ... Which One Should You Use?


Fundamentally, it's a matter of your preferred programming style. The bottom line is getting the program to work correctly and efficiently and both styles do that. But my preferred programming style is Select Case. I find it easier to read and understand than the If structure. To my mind, it's easier to see exactly which statements are executed for every condition.

Frequent About Visual Basic contributor, Peter Zilahy Ingerman adds this reasoning, "Select Case makes writing multiple Or conditions simpler, so that if one begins by having a zillion separate Case statements, and one discovers that there are really only three or four actions, collapsing the Cases under a Select Case is a *whole* lot easier than rewriting the If-ElseIf-...-End structure."

From a performance point of view, there isn't any reason to choose one over the other. I checked using a StopWatch object to time the two examples shown above. Even using ten million random iterations didn't make the time necessary to execute them vary by more than a few hundred milliseconds. As a final check, I looked at the intermediate language (the language that all .NET code is compiled into before execution) for a Release build of both routines. They were almost identical.

Final Thoughts


The lesson here is that even if you do like one coding style over another, the VB.NET compiler will create the most efficient code possible.
Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.