X++ in AX7: Const keyword

In AX7 X++ now supports the const keyword. Semantically it is identical to const in C#.

In short; it allows you to define members on a class and variables in a method that can only be initialized during the declaration. The compiler will replace references to these constants with the literal value. In other words, the constant value must be known at compile time.

This is a killer feature! It replaces most use cases of macros.

void constsAreCool() 
    #define.magicNumber("AX 2012");  
    const str MagicNumber = "AX7";  

There are many benefits:

  1. IntelliSense in the editor.
  2. Support for "Go to definition" in the editor.
  3. Full control of the type for the constant.
  4. Faster compilation – macros are notorious hard for the compiler to handle.
  5. None of the macro idiosyncrasies – like the ability to redefine/override.

Now when you couple this with public and static members, then you can create classes with constants to replace macro libraries.

static class TimeConstants 
    static const public int DaysPerWeek = 7;  
    static const public int HoursPerDay = 24;  
    static const public int HoursPerWeek = TimeConstants::DaysPerWeek * TimeConstants::HoursPerDay;  

It is best practice to use PascalCasing when naming const variables, regardless of if they are private, protected or public.

Notice how the constants in the class are referenced:


This is much clearer than macros:

int x = #HoursPerWeek  

For example; you are no longer in doubt where the definition is coming from.



Comments (5)

  1. Thanks Yury – You will not get a BP error when using const and hard coded values, like 123 or "My string".

  2. Yury says:

    That is really great! Those macroses was a disaster. But how about the BP checks? Will they skip such constants?

  3. The main difference is that const values must be determinable at compile time – where as readonly variables are normal variables, that only can be assigned in the constructor.

  4. NavidAhsan says:

    How is this different to Readonly keyword?

  5. golob says:

    Now, if we could only get rid of #InventDimJoin and friends 🙂

Skip to main content