Odd Code in AX: #if.never

April 7, 2010 at 17:45
filed under Dynamics AX
Tagged , ,

Some lines of code in AX look a bit strange, #if.never is one of those. I notice that some people don’t fully understand what this is for, or don’t know when and how to use it.

Take a look at the following code sample:

static void klforIfNever(Args _args)
{
    ;
    #if.never
        some text or maybe some code:
    i = i++;
    #endif
}

Notice that this will compile although the code between #if.never and #endif has no valid syntax.
How does this work?

The #if macro is one of the built in macro’s in ax. It tests if a macro has been defined.
As you know, you can define a macro like this:

#Define.YourMacro

To test if this macro has been defined, type:

#if.YourMacro

When testing if a macro has been defined, you should end your #if with #endif to make your code compile, just like in the sample job above.

So basically, #if.never is a way to test if the macro named “never” has been defined.

A little side effect of testing whether a macro has been defined using #if and #endif is that if the macro hasn’t been defined, the code in between the #if and #endif will not be compiled or executed. Basically, you can write anything in there, as long as you don’t define the macro (#if.blabla would also work, but #if.never is clearer).

Why would you write code that doesn’t get compiled and executed? Here are two reasons I can think of:

  1. You can use it in interface classes to provide sample code on how the class can be implemented (See: sysPackable).
  2. You can use it as an alternative to commenting out code. Using #if.never will still show your code with markup in stead of everything in green.

So next time you see #if.never, you know what it is for :).

no comments

RSS / trackback

respond