Home› X++ Programming Language› / Programs / Use var Keyword (Language Enhancement)
🚀 Programming Example

Use var Keyword (Language Enhancement)

14 Views
Beginner
Code Snippet
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

💻 Program Code

/// <summary>
/// Use var Keyword (Language Enhancement).
/// </summary>
internal final class Ansari006_VarKeywordDemo
{
    public static void main(Args _args)
    {
        var itemCount = 10;            // int
        var price     = 99.5;          // real
        var product   = "Laptop";      // str
        var isOk      = true;          // boolean

        info(strFmt("%1 x %2 at %3 each, in stock: %4", itemCount, product, price, isOk));
        info(strFmt("Total = %1", itemCount * price));
    }

}

📘 Explanation

Use var Keyword (Language Enhancement)
Figure: Use var Keyword (Language Enhancement)

Use the var Keyword in X++ (Type Inference)

Overview

Modern X++ supports type inference with the var keyword, borrowed from C#. Instead of writing the type of a local variable, you let the compiler work it out from the value you assign. The variable is still strongly typed: once the compiler decides it is an int, it stays an int.

This program declares four variables with var (an integer, a real, a string and a boolean), prints them in one message and multiplies two of them. It shows that var saves typing without losing type safety.

Prerequisites

  • A D365 F&O development environment with Visual Studio, and a model and project to work in.
  • A runnable class: Add > New Item > Dynamics 365 Items > Code > Runnable Class (Job). The class name must match the file name.
  • No tables or setup data are needed. var is available in D365 F&O (it was not available in AX 2012).

Code Walkthrough

1. Declaring variables with var

var itemCount = 10;            // int
var price     = 99.5;          // real
var product   = "Laptop";      // str
var isOk      = true;          // boolean

The compiler looks at each value to decide the type:

  • 10 is a whole number, so itemCount becomes int.
  • 99.5 has a decimal point, so price becomes real.
  • "Laptop" is text, so product becomes str.
  • true is a boolean literal, so isOk becomes boolean.

The comments document the inferred types, which is helpful while you are learning. A var variable must be given a value when it is declared, otherwise the compiler cannot infer its type.

2. Printing all values in one message

info(strFmt("%1 x %2 at %3 each, in stock: %4", itemCount, product, price, isOk));

strFmt() converts each type to text: the real number is shown with two decimals (99.50) and the boolean is shown as Yes or No.

3. Calculating with inferred types

info(strFmt("Total = %1", itemCount * price));

Multiplying an int by a real gives a real (995.00). This works exactly as it would with explicitly typed variables, which proves that var variables have real types.

Key Concepts

  • Type inference: the compiler decides the type from the initial value at compile time, not at run time.
  • Strong typing: after var x = 10;, the statement x = "text"; is a compile error.
  • var vs anytype: anytype can hold any type and changes at run time. var is fixed at compile time.
  • Where var is allowed: local variables only. Class members, method parameters and return types must have explicit types.

Expected Output

10 x Laptop at 99.50 each, in stock: Yes
Total = 995.00

The decimal format depends on your regional settings. Some users will see 99,50.

Best Practices and Common Mistakes

  • Do use var when the type is obvious from the right side, for example var query = new Query();.
  • Do write the type explicitly when it is not obvious, for example AmountMST total = this.calcTotal();. EDTs carry labels and rules that var cannot infer.
  • Do not expect var to infer an EDT. var amount = 99.5; becomes plain real, not AmountMST.
  • Watch out for integer literals: var total = 0; becomes int, so later adding decimals is a problem. Write var total = 0.0; for a real.
  • Be consistent within a team. Many teams use var for objects created with new and explicit types for business values.

Interview Questions

  1. Is a var variable dynamically typed?
    No. Its type is fixed at compile time from the initial value.
  2. Can you declare var without assigning a value?
    No. The compiler needs a value to infer the type.
  3. What is the difference between var and anytype?
    var is a compile-time inferred fixed type. anytype can hold any type and change at run time.
  4. Can var be used for class member variables or parameters?
    No. It can only be used for local variables.
  5. What type does var x = 99.5; get?
    real. It does not become an EDT such as AmountMST.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.