Using a CASE statement to test multiple conditions
When you have more than two conditions to test, it can often be beneficial to use a CASE
statement for better code readability.
How to do it...
Create a new codeunit from Object Designer.
Add the following global variables:
Name
Type
I
Integer
Add the following code to the
OnRun
trigger of your codeunit:i := 2; CASE i OF 1: MESSAGE('Your number is %1.', i); 2: MESSAGE('Your number is %1.', i); ELSE MESSAGE('Your number is not 1 or 2.'); END;
When you run the codeunit you will see a window like the following screenshot:
How it works...
A CASE
statement compares the value given, in this case "i", to various conditions contained within that statement. Each condition, other than the default ELSE
, is followed by a colon. Here it checks if "i" is equal to 1, if "i" is equal to 2, and if "i" is neither 1 nor 2. You would get the same result if you wrote the following code:
IF i = 1 THEN MESSAGE('Your number is %1.', i) ELSE IF i = 2 THEN MESSAGE...