Switch Statement in Salesforce

Salesforce introduced the Switch statement in the Winter’18 release. But still, very less developers are using Switch statements in Salesforce. In this post, we will learn about the switch statement in the apex.

What are Switch Statements?

Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly. In this section, We will provide detailed functional behavior of switch statements with syntax.

What are Switch Statements in Apex

Image found from Salesforce doc

Consideration for Switch Statement in Salesforce

  • The when value can be a single value, multiple values, or sObject types “when value2, value3 { }
  • If no when values match the expression, the when else block is executed.
  • Apex switch statements can be done on one of the following types.
    • Integer
    • Long
    • sObject
    • String
    • Enum
  • No Break: In Apex, we don’t have break statements like we used to have in another programming language.
  • The value null is a legal value for all types
  • Please set the Apex code version as 43

Learn more here.

Apex Switch Example

switch on i {
   when 2, 3, 4 {
       System.debug('when block 2 and 3 and 4');
   }
   when 5, 6 {
       System.debug('when block 5 and 6');
   }
   when 7 {
       System.debug('when block 7');
   }
   when else {
       System.debug('default');
   }
}

Switch Statement example in Trigger

You can use a switch statement in Apex Trigger like below using Trigger.OperationType.

trigger AccountTrigger1 on Account ( before Insert ,Before Update , After Insert, After Update) {
       switch on Trigger.OperationType  {
            when BEFORE_INSERT
            {
                System.debug('BEFORE_INSERT------>' + Trigger.OperationType );
                System.debug(Trigger.OperationType +'-Before Insert-->'+Trigger.isInsert+'--->'+Trigger.isBefore);
            }
            when AFTER_INSERT
            {
                System.debug('AFTER_INSERT ------->' +Trigger.OperationType );
                System.debug(Trigger.OperationType +'-After Insert-->'+Trigger.isInsert+'--->'+Trigger.isAfter);
            }
            when BEFORE_UPDATE, AFTER_UPDATE
            {
                System.debug('BEFORE_UPDATE or AFTER_UPDATE----->' +Trigger.OperationType );
            }
        }
}

Summary

Let us know how you are using the Switch case in your project. If you are new to Salesforce then check out our FREE Salesforce Training.

Amit Chaudhary
Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates.

He is a active blogger and founder of Apex Hours.

Articles: 469

Leave a Reply

Your email address will not be published. Required fields are marked *