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);
}
}
{
static public PersonName fullName(DirPersonName _person)
{
return strFmt(‘%1 %2 %3’, _person.FirstName, _person.MiddleName, _person.LastName);
}
}
Things to remember:
- The class must be postfixed with “_extension”.
- The class must be static.
- The extension methods must be static.
- The type of the first parameter determines which type is extended.
Now you can enjoy your extension method:
DirPersonName dirPersonName;
while select dirPersonName
{
info(dirPersonName.fullName());
}
while select dirPersonName
{
info(dirPersonName.fullName());
}
Notice:
- When calling extension methods, you don’t provide the first parameter – that gets inferred from the instance’s type.
- If the extension method took any additional parameters – they (of course) needs to be provided.
- This doesn’t break encapsulation. The extension method only has access to public fields and methods on the type.
No comments:
Post a Comment