Skip to main content

Notifications

Announcements

No record found.

Dynamics 365 Community / Blogs / mfp's two cents / X++ in AX7: Extension methods

X++ in AX7: Extension methods

1134.AX7TShirt.jpg Have you ever experienced a Microsoft provided class or table missing that vital method that would just make your life easier? If so, you might have been tempted to add it yourself using overlayering. And you surely have paid the upgrade price!

You are about to be pleased. In AX7 X++ supports extension methods, similarly to C#.

Suppose we want to add a fullName method to the DirPersonName table. Here is how you do it, without touching the DirPersonName table. Create this new class:

 

static class MyDirPersonName_Extension
{
    static public PersonName fullName(DirPersonName _person)
    {
        return strFmt('%1 %2 %3', _person.FirstName, _person.MiddleName, _person.LastName);
    }
} 

Things to remember:

  1. The class must be postfixed with "_extension".
  2. The class must be static.
  3. The extension methods must be static.
  4. The type of the first parameter determines which type is extended.

Now you can enjoy your extension method:

while select dirPersonName
{
    info(dirPersonName.fullName());
}

Notice:

  1. When calling extension methods, you don't provide the first parameter – that gets inferred from the instance's type.
  2. If the extension method took any additional parameters – they (of course) needs to be provided.
  3. This doesn't break encapsulation. The extension method only has access to public fields and methods on the type. -

Update - as of Fall release 2016, the syntax is now cleaner - and you can do much more (see here). The above example can be rewritten as:

[ExtensionOf(tableStr(DirPersonName))]
final class MyDirPersonName_Extension
{
    public PersonName fullName()
    {
        return strFmt('%1 %2 %3', this.FirstName, this.MiddleName, this.LastName);
    }
}

THIS POST IS PROVIDED AS-IS AND CONFERS NO RIGHTS.

Comments

*This post is locked for comments