Implement global functions in X++

Completed

You can implement global functions as static methods in the Global class, and you can use them in an application.

Create new global functions in X++

To create new global functions with a code extension of the Global class, follow these steps:

  1. Find the Global class in Application Explorer.

  2. Right-click the Global class to open the context menu, and then select Create Code Extension.

    Note

    The Global class belongs to the Application Platform model, and your model must reference it.

    A code extension is now created in your project.

  3. The Global class is static, so you must use the static modifier in the class description.

  4. Add the new method as a static method. The following example shows a new global method:

     [ExtensionOf(classStr(Global))] 
     final static class Global_MB500_Extension
     {
         /// <summary>
         /// Add a with b
         /// </summary>
         /// <param name="a">
         /// First number to add
         /// </param>
         /// <param name="b">
         /// Second number to add.
         /// </param>
         /// <returns>
         /// A + B.
         /// </returns>
         static real addAandB(real a, real b)
         {
             return a + b;
         }
     }
    
  5. Build your project by using the new global function.

Extend a global function

You can extend existing global functions by using Chain of Command. The following example shows an extended method that uses Chain of Command:

   /// <summary> 
   /// Add MB-500 to formCaption
   /// </summary>
   /// <param name="formName">
   /// formName
   /// </param>
   /// <returns>
   /// MB-500 form caption.
   /// </returns>
   static str formCaption(FormName formName)
   {
       str txt = next formCaption(formName);

       return 'MB-500 ' + txt;
   }

The system extends the formCaption method and then returns MB-500 and the normal formCaption.

Call a new global function

You can call global functions without using the class name. Normally, the syntax for using static methods is className::MethodName, such as MyClass::MyMethod. However, you can call all global functions by using only the method name.

The following example shows a call to your newly created global function:

internal final class RunnableClass1 
{
    /// <summary>
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
        real    mySum = addAandB(100, 500);

        Info(strFmt("%1", mySum));
    }

}

Global functions are straightforward to use, and you don’t need to enter the class name in code.