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 enumenum Button { ON, OFF }// declaring a variable of type enumButton button;// function to turn on the buttonfunction buttonOn() public {// set the value of button to ONbutton = Button.ON;}// function to turn off the buttonfunction buttonOff() public {// set the value of button to OFFbutton = Button.OFF;}// function to get the value of the buttonfunction getbuttonState() public view returns(Button) {// return the value of buttonreturn 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.