How do you create and use methods in X++?

Rumman Ansari   Software Engineer   2023-10-19   1484 Share
☰ Table of Contents

Table of Content:


How do you create and use methods in X++?

In X++, a method is a block of code that performs a specific task and can be called by other parts of the code. Methods can take parameters as input and can return a value as output.

Here's an example of how you might create a method called "myMethod" that takes an integer parameter called "x" and returns the square of the value:


int myMethod(int x)
{
    return x*x;
}

Once you have created a method, you can call it from other parts of your code by using the method name followed by parentheses and any necessary parameters. Here's an example of how you might call the "myMethod" method and store the result in a variable:


int result = myMethod(5);

It's also worth mentioning that X++ methods can have different types of visibility, such as public, protected, or private. Public methods can be accessed from any class, protected methods can be accessed from the same class and its subclasses and private methods can only be accessed from the same class.

Additionally, X++ also supports method overloading, that is the ability to have multiple methods with the same name but with different parameters. This can be useful when you want to provide different implementations for a method based on the input parameters.

It's important to keep in mind that, when creating methods, it's important to choose meaningful and descriptive method names that indicate the purpose of the method, and to use clear and consistent parameter names and types. Also, it's important to document the methods using the appropriate comment tags, to help other developers understand how to use them correctly.

Default access level of method is public.

A method that is not modified with public, protected, or private has the default access level of public.

VehicleClass

class VehicleClass
{
   // Instance fields.
   real height;
   real width;
  
   // Constructor to initialize fields height and width.
   void new(real _height, real _width)
   {
       height = _height;
       width = _width;
   }
 
   //Default access level of method is public.
   int add(){
           return this.height + this.width;
   }
}


AccessVehicleClass

internal final class AccessVehicleClass
{
   /// <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)
   {
       VehicleClass vcObj = new VehicleClass(12.0, 10.0);
       info(strFmt("%1", vcObj.add()));
   }
 
}