X++ Control Statements
X++ Control Statements
Introduction
This course explains how to use control statements in X++. These statements
control the logic flow in the program. This course also describes how to use some
built-in functions in Microsoft Dynamics® AX to communicate with the end-user.
Scenario
Isaac, the Systems Developer, is implementing a project that requires a
modification to code. He has been asked to become familiar with the typical
statements in X++ used to control program flow, and to communicate with the
user.
2-1
Development II in Microsoft Dynamics® AX 2012
Introduction to Variables
Variables hold data when a block of code executes. Variables all have scope.
Scope is the area where the variable can be accessed. Some different types of
scope include:
Scope Description
Global (to a class) These are variables defined in the classDeclaration
of a class.
Local (to a method) These are variables defined in a method of a class.
Local (to an embedded These are variables defined in a function embedded
function) in a method of a class.
Use the type of variable that matches the type of data that you want to store. You
can name the variable, as long as you do not use names the system already uses,
such as commands or keywords. A list of reserved words is located in the
Developer Help under the "Keywords" lesson.
BEST PRACTICE: Do not use names like string1. Always give a variable a
meaningful name so its use is easier to identify when reading the code.
Declaration
All variables must be declared before use. When a variable is declared, a small
amount of memory is reserved. The syntax of the declaration is the same,
whether it is a simple variable or an object variable.
You cannot mix variable declarations with other X++ statements. Variables must
be declared before the statements.
You might want a variable to have a value other than the default when the
variable is declared. X++ supports initialization of variables in the Declaration
statement. Initialization is performed by adding the assignment-statement to the
variable declaration. For example:
2-2
Chapter 2: X++ Control Statements
The following table provides an overview of the simple data types available in
Microsoft Dynamics AX:
2-3
Development II in Microsoft Dynamics® AX 2012
dataType variableIdentifier;
The data type can be any of the data types in X++. Here are some examples:
int integerVariable;
real realVariable;
str unboundStringVariable;
str 30 boundStringVariable; // max of 30 chars
date dateVariable;
boolean booleanVariable;
When declaring a variable, you can also declare them as an extended data type.
This is a good practice because it can highlight errors in code at compile time
when a variable is used incorrectly.
It is common to name the variable the same as the extended data type, when
possible.
custAccount custAccount;
transDate transDate;
amountMST amountDebit, amountCredit;
Initializing Variables
The following statements show how to declare the variables for use later in the
code. You can declare several variables of the same type with different names.
You can also assign a value to the variable when you declare it or later in the
code.
2-4
Chapter 2: X++ Control Statements
Arrays
Arrays can be declared by adding brackets ( [ ] ).
You can set the maximum number of array elements by putting the number in the
brackets.
Array values can be set by specifying the index when assigning the value.
realLimitedArray[2] = 3.142;
Containers
A container variable can contain different types and values of simple and
extended data types, including arrays and other container variables. Classes
cannot be put into containers.
There are many functions that manipulate container variables. The following
functions are available:
Function Description
conPeek Returns the value being held in a specific position in the
container.
conDel Removes a value from a specific position in the container.
conNull Returns an empty container.
2-5
Development II in Microsoft Dynamics® AX 2012
Function Description
conFind Finds the position in the container that a certain value is
being held (if found).
conIns Inserts a value into a specific position in the container.
conPoke Replaces the value being held in a specific position in the
container, with a new value.
conLen Returns the number of elements in the container.
The following examples have a container variable that contains four values,
including three different data types.
Operators
Operators are used to manipulate variable and field values and to control the
logical program flow based on the values in variables and fields. The following
types of operators are available.
Assignment Operators
Assignment operators modify the contents of a variable or field. The following
table defines available operators.
Operator Description
= Assigns the expression on the right of the equal sign to the
variable on the left.
+= Increments the variable on the left by the value on the right.
++ Increments the variable on the left by one.
-= Decrements the variable on the left by the value on the right.
-- Decrements the variable on the left by one.
2-6
Chapter 2: X++ Control Statements
Arithmetic Operators
Arithmetic operators perform calculations in X++. Arithmetic operators are used
like relational operators except for '~, ++, --, +=, and -='. The following table
defines available arithmetic operators:
The following are some examples of these arithmetic operators. For all examples,
the variable 'i' is an integer.
2-7
Development II in Microsoft Dynamics® AX 2012
NOTE: View more examples of arithmetic operators in the "X++ Online Help
Guide."
Relational Operators
Relational operators, except for '!', are placed between two expressions. The
following table defines available relational operators:
2-8
Chapter 2: X++ Control Statements
The following are examples using relational operators and their return values:
Operator Precedence
You can use X++ to create complex statements using multiple operators when
data types on all parts of the statements are equivalent. When multiple operators
are used in one statement, precedence for the operators must be in place for
statement evaluation. The following table lists the precedence for operators. The
highest precedence is at the beginning of the table; precedence gets lower as you
move down the table.
2-9
Development II in Microsoft Dynamics® AX 2012
Conditional Statements
Conditional statements in programming define conditions under which certain
functions are performed. Conditional statements use logical expressions that are
evaluated and return a value of either true or false. There are three primary
conditional statements:
• If statement
• Switch statement
• Ternary operators
If
The if statement is the simplest control statement. It checks whether a condition
is true or false. If the condition is satisfied, all the code within the braces '{}' is
executed. The syntax for an if statement is as follows:
if (condition)
{
//if true these statements are executed
}
if (a > 10)
{
print a;
}
2-10
Chapter 2: X++ Control Statements
If...else
An if statement checks for only one possibility and ignores all other conditions.
An if…else statement checks one condition and if true, the block of code is
executed. Otherwise, an alternative statement is executed. The syntax for an
if…else statement is as follows:
if (condition)
{
//if true these statements are executed
}
else
{
//if false these statements are executed
}
int i = 12;
int j = 10;
int max;
if (i > j)
{
max = i;
}
else
{
max = j;
}
The previous conditional formulas allow for only two alternative outcomes. A
program might have to check more than two alternatives. To check for multiple
alternatives, you can use an if…else...if statement. The syntax for this statement
is as follows:
if (condition1)
{
//statement1
}
else
{
if (condition2)
{
//statement2
}
else
{
//statement3
}
}
2-11
Development II in Microsoft Dynamics® AX 2012
You might need to have a condition in a condition. You can do this using nested
if statements.
1. If the student has failed the exam, then the student fails the course.
2. If the student has passed the exam, then check the student's
homework sections.
3. If the student has passed the exam and the homework sections, the
student passes the course.
4. Otherwise, the student fails.
if (passExam == true)
{
if (passHomeWork == true)
{
studentStatus = "Passed";
}
else
{
studentStatus = "Failed";
}
}
else
{
studentStatus = "Failed";
}
Ternary Operator
This conditional statement behaves exactly like an if…else statement. The main
reason to use the ternary operator is convenience in coding. Its syntax is as
follows:
2-12
Chapter 2: X++ Control Statements
This example using the ternary operator, is equivalent in logic and results to the
previous example using the if...else statement.
int i = 12;
int j = 10;
int max;
max = i > j ? i : j;
Switch
A switch statement acts as a multi-branch control statement that defines an
expression and whose result leads to a specific program execution. The switch
statement considers the result and executes code, depending on possible
outcomes of the expression. These are known as cases. Each of these cases is
listed in the body of the statement.
Following the colon after each case are statements that execute if the expression
satisfies the case. There can be any number of statements following a case in a
switch statement. The body of a switch statement is enclosed in braces '{}'. The
following shows the syntax for a switch statement:
switch (expression)
{
case 'Choice1':
Statement1;
Statement2;
break;
case 'Choice2':
Statement3;
break;
case 'Choice3':
Statement4;
Statement5;
Statement6;
break;
default : DefaultStatement;
}
The break; statement tells the program to leave the switch statement and
continue immediately after the switch. This can also be used elsewhere in X++
coding. The default case executes if the result of the expression does not match
any of the cases. Using the default case is optional.
2-13
Development II in Microsoft Dynamics® AX 2012
For these examples, students receive a score from a test. The score must have a
corresponding letter grade. The scores can only be 90, 80, 70, and so on.
switch (score)
{
case 90 : grade = "A";
message = "Excellent";
break;
case 80 : grade = "B";
message = "Good";
break;
case 70 : grade = "C";
message = "Average";
break;
case 60 : grade = "D";
message = "Poor";
break;
default : grade = "Failed!";
message = "You need to study more!" ;
}
This example produces the same result as the previous example, but uses if...else
statements instead of the case statement. Note the number of lines of code and
the ease of reading the code in each case.
if (score == 90)
{
grade = "A";
}
else
{
if (score == 80)
{
grade = "B";
}
else
{
if (score == 70)
{
grade = "C";
}
else
{
2-14
Chapter 2: X++ Control Statements
if (score == 60)
{
grade = "D";
}
else
{
grade = "Failed!";
}
}
}
}
As illustrated on the previous page, the switch statement simplifies the code and
makes the program flow more efficiently. Another advantage of using a switch
statement is allocating multiple results of the expression to one outcome or case.
The following example shows the use of multiple expressions in a switch
statement.
switch (color)
{
case "red", "yellow", "blue" :
colortype = "Primary Color";
break;
2-15
Development II in Microsoft Dynamics® AX 2012
This example produces the same result as the previous example, but uses if...else
statements instead of the case statement. Note the number of lines of code and
the ease of reading the code in each case.
if ((color =="red")
|| (color =="yellow")
|| (color =="blue"))
{
colortype ="Primary Color";
}
else
{
if ((color =="purple")
|| (color =="green"')
|| (color =="orange"))
{
colortype ="Secondary Color";
}
else
{
colortype ="Neither Primary or Secondary color"
}
}
Loops
Repetitive statements, also known as loops, conditionally control data input and
output. There are three main loops in X++:
• While loop
• Do while loop
• For statement
While
The while loop evaluates a condition and executes statements, depending on
whether the condition is satisfied. The loop continues to check the condition, and
as long as the condition is true, it continues to execute the statements. As soon as
the condition becomes false, the statement is exited. The syntax is as follows:
while (condition)
{
//statement;
}
2-16
Chapter 2: X++ Control Statements
int counter = 1;
pause;
Result:
HINT: The previous example uses the counter++ which can increment any
integer by 1. You can also set the increment to any value by using the
variable+=<# to increment> syntax. For example:
counter+=2; //This increments the counter variable by two every time.
Notice the condition is evaluated before the statements are executed. In the
previous example, it means that if the counter variable is greater than five when it
reaches this loop, it does not execute. Therefore, a while statement can be
executed zero or more times.
Do...while
The function of a do while statement is almost identical to the while statement.
The main difference is that the condition is evaluated after the statement
executes. The effect is that the loop always runs at least one time. The following
is the syntax for a do while statement:
do
{
//statement;
}
while (condition);
2-17
Development II in Microsoft Dynamics® AX 2012
For
The for statement uses an incrementing counter variable, and a condition, to
determine the how long it will continue to loop. The parameters in a for
statement include three elements:
For loops are frequently used when navigating through an array. The following
is an example of how to use a for loop to print each element of a string array
called 'abc' that contains 10 strings:
A for loop and a while loop perform the same function. However, the for loop is
more condensed in structure. In a while loop, if the counter variable is not
incremented, an infinite loop can occur. This is not possible with a for loop
because you receive a syntax error if that part of the condition is not qualified.
The break statement completely interrupts a loop at any time. The best example
of a break is in a switch statement.
2-18
Chapter 2: X++ Control Statements
The continue statement ignores the rest of the current loop and continues to
control the loop. The following example uses a for loop with the continue
statement to control which values print to the screen. The loop executes the print
statement for values <= 3 and >= 8.
int counter;
Result:
10
2-19
Development II in Microsoft Dynamics® AX 2012
Isaac has been asked to demonstrate the use of a while statement by printing out
the multiplication table for 2.
Challenge Yourself!
1. Create a job that prints the multiplication table for 2 using a while
statement.
2. Have the list contain all even numbers up to 50.
3. Use a 'counter' variable to increment every time.
Step by Step
int counter = 1;
pause;
2-20
Chapter 2: X++ Control Statements
Isaac has been asked to demonstrate the use of a do...while statement by printing
out the multiplication table for 2.
Challenge Yourself!
Step by Step
int counter = 1;
do
{
print counter * 2;
counter++;
}
while(counter <= 25);
pause;
2-21
Development II in Microsoft Dynamics® AX 2012
Isaac has been asked to demonstrate the use of a for statement by printing out the
multiplication table for 2.
Challenge Yourself!
1. Create a job that prints the multiplication table for 2 using a for
statement.
2. Have the list contain all even numbers up to 50.
3. Use a 'counter' variable to increment every time.
Step by Step
int counter;
pause;
2-22
Chapter 2: X++ Control Statements
Built-in Functions
Microsoft Dynamics AX contains many built-in functions to help in X++
development. These functions perform mathematical operations, convert data
types, return system values, and so on.
Built-in functions can be used anywhere in X++ code. These functions can be
typed manually or accessed by using the context (right-click) menu in the Code
Editor and selecting List Built-in Functions, or by pressing Shift+F4.
To use a function, click it. The function is placed in the code where the pointer is
located.
This example uses a function that returns a subset of a string variable. The syntax
for the function is as follows:
Component Description
str substr Specifies the return type of the function (string) and the
name of the function (subStr).
str text The original text string.
int position Indicates the position where the sub-string starts.
int number Designates how many characters are included in the sub-
string.
str letters;
letters = "ABCDEFG";
print subStr(letters, 2, 4);
print subStr(letters, 5, -3);
pause;
BCDE
CDE
The negative number causes the characters to be selected backward from the
position.
2-23
Development II in Microsoft Dynamics® AX 2012
Communication Tools
Communicating with the end-user is important and critical for an application to
run correctly. The main types of communication include:
• Forms and reports used for input and output of larger amounts of
data.
• Print statements, Infologs and dialog boxes generally used for
specific data input and output.
This lesson discusses how to use the print statement, create dialog boxes and
Infologs. Forms and reports are covered in more detail in the next development
course.
Print...Pause
When the compiler reaches a print statement, it returns whatever value or
variable value that immediately follows the print syntax. The following is an
example of the print statement:
The pause line freezes the output text on the screen after the code runs so that it
is easier to read. The pause statement causes a message box to pop up. It lets the
user continue or end code execution.
The print statement should not be used within the actual application business
logic. It is used only as a programmers tool to display data or values while
developing and debugging code.
Boxes
Boxes display brief messages to application users. There are many box types and
each has their own box method.
The following is an example of an information box and how the parameters are
used:
2-24
Chapter 2: X++ Control Statements
The string "This is the help text" appears in the status bar at the bottom of the
screen.
The box class contains many methods that create different types of boxes. These
methods can be viewed in the AOT under Classes > Box. Many boxes only
provide output to the user, whereas other boxes accept input from the user,
depending on which button the user clicks.
Some of the more commonly used boxes are discussed in this lesson.
The warning box is used to display warning messages. The following example
shows how the warning message is used:
2-25
Development II in Microsoft Dynamics® AX 2012
The following is an example of how X++ accepts user input and executes
statements based on this input:
DialogButton dialogButton;
if (dialogButton == DialogButton::Yes)
{
print "You chose Yes";
pause;
}
else if (dialogButton == DialogButton::No)
{
print "You chose No";
pause;
}
The box function returns a value of the enum DialogButton that can be used to
determine which option the user chooses.
Infolog
The Infolog is the most common method used to communicate with the user
about how a process is executed. Boxes can output a message to a user. However,
sometimes multiple messages are generated during processing. Infologs are more
suited to handle multiple messages; there are three types of messages:
2-26
Chapter 2: X++ Control Statements
The following table contains Infolog icons and a description of each method.
The easiest way is to use the info (text) function. This adds the text to the Infolog
system. Any text that is added to the Infolog is displayed when the program
returns to a state of waiting for user input. This is typically at the end of a
process.
warning("Infolog text");
error("Infolog text");
2-27
Development II in Microsoft Dynamics® AX 2012
The Infolog system is used mostly to display multiple messages at the same time,
in tree form. The following figure shows an example of multiple messages in tree
form.
The setPrefix() function sets the label for the heading of the Infolog tree. In the
example, it specifies the label, 'Infolog Tree'. The following example shows the
syntax of this method:
setPrefix("Infolog Tree");
2-28
Chapter 2: X++ Control Statements
The following figure shows how adding calls to setPrefix() adds multiple levels
to the Infolog tree. The level will continue while the method the setPrefix()
statement is called in remains in scope.
BEST PRACTICE: Use labels when possible for the text of these Infolog
messages and the SetPrefix function.
Dialog Boxes
Dialog boxes are a simplified type of form in Microsoft Dynamics AX, and they
are generated from the Dialog class. They create a dialog with the user where the
user can input values. Dialog boxes are not used in complex scenarios; forms are
the preferred method in complex situations. All dialog boxes have a standardized
form that contains an OK/Cancel option.
NOTE: The Dialog class described here is a different concept then the Dialog
Form Template available as a context-menu option on the Form node in the
AOT. This topic describes creating Dialog forms using X++ code.
2-29
Development II in Microsoft Dynamics® AX 2012
The following example displays the dialog box and prints the value entered to the
screen.
if (dialog.run())
{
print dialogField.value();
pause;
}
}
2-30
Chapter 2: X++ Control Statements
Isaac has been asked to create a job that will prompt the user to continue or
cancel. The user should be asked whether he or she wants to continue and be able
to choose Yes or No.
Challenge Yourself!
Create a new job in the AOT that contains a box where the user can decide to
continue or cancel.
Step by Step
DialogButton dialogButton;
2-31
Development II in Microsoft Dynamics® AX 2012
Isaac has been asked to create an Infolog Tree that has an Info message, a
Warning message and an Error message.
Challenge Yourself!
Create a tree of Infolog messages using a job in Microsoft Dynamics AX. The
tree should have a root node which states: "This is the Infolog Tree lab." The tree
should contain at least one of each type of message (Info, Warning and Error).
Step by Step
2-32
Chapter 2: X++ Control Statements
Isaac has been asked to create a dialog box that will prompt the user to enter a
customer account number and a sales order ID.
Challenge Yourself!
Create a dialog box that lets the user select a customer account number and a
sales order ID. Once the user clicks OK, show the values of each selection using
the Infolog.
Step by Step
Dialog dialog;
DialogGroup dialogGroup;
DialogField dialogFieldCustAccount;
DialogField dialogFieldSalesId;
if(dialog.run())
{
info(dialogFieldCustAccount.value());
info(dialogFieldSalesId.value());
}
2-33
Development II in Microsoft Dynamics® AX 2012
Isaac has been asked to create a job that will ask the user if he or she wants to
display his or her date of birth. If the user chooses Yes, the system should print
the user's name and date of birth. If the user chooses No, the system should only
print the user's name.
Challenge Yourself!
Create a dialog for the user that determines, based on input, what appears on a
screen.
Step by Step
DialogButton dialogButton;
container nameAndDOB;
nameAndDOB = ["John","Doe",mkDate(28,9,71)];
dialogButton = Box::yesNo("Do you want to see the
birthdate?", DialogButton::Yes);
if (dialogButton == DialogButton::Yes)
{
Box::info(strFmt("%1 %2, %3", conPeek(nameAndDOB,1),
conPeek(nameAndDOB,2), date2str(conPeek(nameAndDOB,3),-1,-
1,-1,-1,-1,-1)));
}
else
{
Box::info(strFmt("%1 %2",conPeek(nameAndDOB,1),
conPeek(nameAndDOB,2)));
}
2-34
Chapter 2: X++ Control Statements
Note the use of mkDate and strfmt functions. MkDate ("make date") returns a
date from the parameters day, month and year. Strfmt ("string format") inserts
any type of value into a string.
2-35
Development II in Microsoft Dynamics® AX 2012
Summary
This course introduced three conditional statements and three repetitive
statements. Depending on whether the conditions are true, different commands
can be executed.
This course also showed how the built-in functions can help when writing X++
code to perform mathematical operations, convert data types and so on.
Additionally, to communicate with the end-user, this course showed how to use
the Print Statement, the Box Class, the Infolog System and the Dialog Box.
2-36
Chapter 2: X++ Control Statements
2. Which arithmetic operator would you use to output the remainder when
dividing 83 by 10 and what would the syntax be?
2-37
Development II in Microsoft Dynamics® AX 2012
4. What is the function 'mthName' used for? What is its syntax? Give an
example using this function.
2-38
Chapter 2: X++ Control Statements
1.
2.
3.
2-39
Development II in Microsoft Dynamics® AX 2012
Solutions
Test Your Knowledge
1. What are the three primary types of conditional statements in X++?
MODEL ANSWER:
2. Which arithmetic operator would you use to output the remainder when
dividing 83 by 10 and what would the syntax be?
MODEL ANSWER:
MOD
83 Mod 10
MODEL ANSWER:
2-40
Chapter 2: X++ Control Statements
4. What is the function 'mthName' used for? What is its syntax? Give an
example using this function.
MODEL ANSWER:
'mthName' is used to return the month name based on the number specifying
the month. Its syntax is as follows:
str mthName (int month);
Example
mthname(1); //returns "January"
MODEL ANSWER:
2-41
Development II in Microsoft Dynamics® AX 2012
2-42