Tuesday, January 24, 2017

Extension methods in X++

In Dynamics 365 for operations (D3FO), one of the main emphasis of Microsoft is to develop extensions and avoid doing any customization to standard objects shipped by Microsoft. A new X++ feature called  Extension Methods is introduced to enable developers to create new methods for standard AX objects without customising them.

Extension methods comes from C# where they enable you to "add" methods to existing types without modifying the original type. These are a special kind of static method which are called as if they were instance methods on the extended type.  MSDN reference Extension methods in C#

In context of AX, extension methods have similar characterstics. Lets take a very common exmaple. If we have to create a new method on a  customer table which returns the customer name and telephone number as one concatened string. Normally we would create a new method on a standard CustTable object which will return the required result somehting like below.




Now there is nothing wrong in such method till AX2012 version but in the new AX (D3FO) doing this will fall under the umbrella of customising the standard AX object. This is not recommended in D3FO as it comes with lot more pains on managing such developments when installing new updates and upgrading the system.

Now in order to do this as an extension we will need to do the following:

1. Create a new static class. The class name should end with suffix _Extension
2. Creat a new static method which returns the type of data you want.
3. In this method definition the first parameter will be the CustTable object as shown below.


Now we can use this method as a table method when writing code. See below the intellisense will show the new method as a list of available method for that object.



By taking the above approach we can develop new methods and reference them via standard objects in our code without customising the objects. This is in alignment with Microsoft's recommendations for development via extensions.