3

Enums in APEX

Enums in Apex are a unique construct for defining a collection of constants. It is an abstract data type with values that each take exactly one value from the finite set of identifiers you specify.

It provides a clear and concise way to represent a fixed set of values. Using enums can make your Apex code more readable and maintainable. They also ensure values are restricted to predefined options, reducing errors and simplifying code decision-making.

How to Define an Enum?

Enums in Apex are defined using the enum keyword. An enum is a particular data type that enables a variable to be a set of predefined constants. The syntax for defining an enum is straightforward:

public enum Season { WINTER, SPRING, SUMMER, FALL }

Enum Methods

You can create your enum or use one of the built-in enums that Apex provides, such as LoggingLevel. User-defined methods cannot be added to Apex enums. Only the built-in standard methods (values(), valueOf(), name(), ordinal()) are available.

All Apex enums, whether user-defined or built-in (such as LoggingLevel), support the following standard enum methods in Apex:

S.No Function Example
1 values This method returns the values of the Enum as a list of the same Enum type. List seasons = Season.values(); System.debug(seasons); // Outputs: (WINTER, SPRING, SUMMER, FALL)
2 valueOf(string enumStr) This method converts a specified string to an enum constant value. An exception is thrown if the input string doesn’t match an enum value. Season season = Season.valueOf('SUMMER');
System.debug(season); // Outputs: SUMMER
3 name Returns the name of the Enum item as a String. String seasonName = Season.SUMMER.name();
System.debug(seasonName); // Outputs: SUMMER
4 ordinal Returns the position of the item, as an Integer, in the list of Enum values starting with zero. Integer position = Season.SUMMER.ordinal();
System.debug(position); // Outputs: 2
Salesforce Developer Training CTA
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Frequently Asked Questions

Why do we use enums in Salesforce?

Enums in Salesforce are used to define named constants, making code more readable, maintainable, and less error-prone.

What are enum methods in Apex?

The major enum methods in APex are values(), valueOf(String), name(), and ordinal().

Can we assign values to enums in Apex?

No, you cannot assign custom numeric or string values to an enum in Apex. Enum constants in Apex are named identifiers.

What is the difference between an enum and a constant?

An enum in Apex is a group of related named constants defined as a single type. On the other hand, a constant is a single fixed value declared with “Final”.

Book Free15-Minutes Career Counselling