Udostępnij za pośrednictwem


Comparison of if and switch Statements

Applies To: Microsoft Dynamics AX 2012 R3, Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012

With X++ there are situations where the switch statement can be a good alternative to the if statement.

Example 1

When you need your X++ code to branch based on one of several values of a single variable, a switch statement can be a less verbose alternative to the if statement. The following table contains an example of each statement.

if statement

switch statement

static void ConditionalJob1i(Args _args)
{
    int account = 1000;

    if (account == 200)
    {
        print "a";
    }
    else if (account == 500)
    {
        print "b";
    }
    else if (account == 1000)
    {
        print "c";
    }
    else if (account == 2000)
    {
        print "d";
    }
    else
    {
        print "e";
    }

    pause;
}
static void ConditionalJob1s(Args _args)
{
    int account = 1000;

    switch (account)
    {
        case 200:
            print "a";
            break;
        case 500:
            print "b";
            break;
        case 1000:
            print "c";
            break;
        case 2000:
            print "d";
            break;
        default:
            print "e";
            break;
    }
    pause;
}

Example 2

When your X++ code must branch based on groups of values for a variable, the switch statement can be a less verbose alternative to the if statement. The following table contains an example of each statement.

if statement

switch statement

static void ConditionalJob2i(Args _args)
{
    int firstNumber = 210;
    int numDivTen = firstNumber / 10;

    if ((numDivTen == 10) ||
        (numDivTen == 12) ||
        (numDivTen == 14)
       )
    {
        print "f";
    }
    else
    {
        if ((numDivTen == 13) ||
            (numDivTen == 17) ||
            (numDivTen == 21) ||
            (numDivTen == 500)
           )
        {
            print "g";
        }
        else
        {
            print "h";
        }
    }

    pause;
}
static void ConditionalJob2s(Args _args)
{
    int firstNumber = 210;

    switch (firstNumber / 10)
    {
        case 10,12,14:
            print "f";
            break;
        case 13,17,21,500:
            print "g";
            break;
        default:
            print "h";
            break;
    }
    pause;
}

Aa842207.collapse_all(en-us,AX.60).gifbreak Statement

If you do not use the break statement, the program flow in the switch statement continues to the next case. The two code segments in the following table have the same behavior.

break omitted

Values are comma-delimited

case 13:
case 17:
case 21:
case 500:
    print "g";
    break;
case 13,17,21,500:
    print "g";
    break;

See also

Conditional Statements

Announcements: New book: "Inside Microsoft Dynamics AX 2012 R3" now available. Get your copy at the MS Press Store.