2017-06-24 - In IL: VB Grade Analyser (Select)
In IL
- Part 1 - Introduction
- Part 2 - Variables and Types
- Part 3 - Variables in Visual Basic .NET
- Part 4 - Instructions and the Stack
- Part 5 - Volume of a Cylinder (Operations)
- Part 6 - Branching Instructions
- Part 7 - Largest of Two Numbers (if-else)
- Part 8 - Largest of Three Numbers (If-ElseIf-Else)
- Part 9 - Switch instruction
- Part 10 - Grade Analyser (switch)
- Part 11 - Prize Calculator (switch-2)
- Part 12 - VB Grade Analyser (Select)
- Part 13 - Loop Instructions
- Part 14 - Print the Alphabet (while)
- Part 15 - Print the Alphabet (do while, for)
- Part 16 - Print the Alphabet (Do Until)
- Part 17 - Print the Alphabet (break, continue)
- Part 18 - Array Instructions
- Part 19 - Summing Arrays
- Part 20 - Other Instructions
- Part 21 - Assemblies
- Part 22 - Class Definitions
- Part 23 - C# Classes and Structs
- Part 24 - VB Classes, Modules and Structures
- Part 25 - Field Definitions
- Part 26 - Field Declarations
The Visual Basic .NET Select statement is a lot like the C# switch statement. The two have similar syntax and are used for similar purposes but the VB version provides more options. For example the C# switch statement requires exact values where as the VB Select statement allows you to enter conditionals.
Let's start by looking at a Select statement which performs the same operations as the switch statement from part 10.
As you can see the syntax of the Select statement is very much like that of the switch statement. Now let's look at the generated IL.
The generated IL for the Select statement looks almost identical to that generated for the switch statement. This is to be expected since the two programs are doing the same thing.
Now we're going to change the program to take numerical ranges instead of characters.
This program isn't that different from the first one except for the variable being checked and the cases. If we compile this into IL however we see it's quite a bit different.
Gone is the switch instruction and the individual cases. Now we have a series of jumps. If you go back a few parts this actually looks like an If-ElseIf ladder. Which is how we would likely write this kind of code in C#. This goes back to what I've said before which is that the compiler is there to help you and make things easier. You don't need a Select statement which can accept ranges because you can already do that using If Else statements and the generated code will be the same in either case. The benefit of the Select statement accepting ranges is not in what it allows you to do but in how it allows you to express what you want to do.
Next time we are going to start looking at loops.
Comments: