Switch Case in X++ Programming Language

Rumman Ansari   Software Engineer   2023-10-25   8873 Share
☰ Table of Contents

Table of Content:


In X++, the switch statement is used to perform different actions based on different conditions. It allows you to test a variable or an expression against a number of possible cases, and execute a block of code when a match is found.

Here's an example of how you might use a switch statement to check the value of a variable called "x" and print a message based on that value:


int x = 5;
switch (x)
{
    case 1:
        info("x is 1");
        break;
    case 2:
        info("x is 2");
        break;
    case 3:
        info("x is 3");
        break;
    default:
        info("x is not 1, 2 or 3");
}

In this example, the switch statement tests the value of the variable "x" against the cases "1", "2", and "3". If a match is found, the corresponding block of code will be executed. If no match is found, the default case will be executed.

It's also worth noting that in X++, the switch statement allows you to use any expression that can be implicitly casted to an integer, this means you can use string or enum variables as well.

Also, the break statement is used to exit the switch statement and transfer control to the next statement after the switch statement. If you don't include a break statement, the execution will continue with the next case, this can be useful


Syntax


switch (expression) {
 case value1:
                   // statement sequence
                   break;
  case value2:
                   // statement sequence
                   break;
.........................
.........................
.........................
  case valueN: 
                   // statement sequence
                   break;
  default:
                   // default statement sequence
}
 

Example Code


// switch case making example x++

static void Examples(Args _args)
{ 
    int number=20;
    
    switch(number){
    case 10: 
            info("case 10 ");
	        break;
    case 20: 
            info("case 20 ");
            break;
    case 30: 
            info("case 30 ");
	         break;
    default: 
            info("Not in 10, 20 or 30");
    }
}