In Solidity, enums stand for Enumerable
. Enums are user-defined data types that restrict the variable to have only one of the predefined values.
The predefined values present in the enumerated list are called enums. Internally, enums are treated as numbers. Solidity automatically converts the enums to unsigned integers.
An enum should have at least one value in the enumerated list. This value cannot be a number (positive or negative) or a boolean value (true or false).
enum <enum-name> {
value1,
value2,
...
}
In the code snippet below, we will see how we can create an enum in Solidity.
pragma solidity ^0.5.0; contract Example { // creating an enum enum Button { ON, OFF } // declaring a variable of type enum Button button; // function to turn on the button function buttonOn() public { // set the value of button to ON button = Button.ON; } // function to turn off the button function buttonOff() public { // set the value of button to OFF button = Button.OFF; } // function to get the value of the button function getbuttonState() public view returns(Button) { // return the value of button return button; } }
Example
.Button
.button
of the enum
type.buttonOn()
to turn on the button.buttonOff()
to turn off the button.getButtonState()
to get the value of the button.buttonOn()
function, the value of the button will be set to Button.ON
.buttonOff()
function, the value of the button will be set to Button.OFF
.getButtonState()
function, the value of the button will be returned.RELATED TAGS
CONTRIBUTOR
View all Courses