What are enums in Solidity?
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).
Syntax
enum <enum-name> {
value1,
value2,
...
}
Code
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;}}
Explanation
- Line 3: We create a contract named
Example. - Line 5: We create an enum named
Button. - Line 8: We declare a variable
buttonof theenumtype. - Line 11: We create a function
buttonOn()to turn on the button. - Line 16: We create another function,
buttonOff()to turn off the button. - Line 21: We create a third button,
getButtonState()to get the value of the button.
Output
- When we call the
buttonOn()function, the value of the button will be set toButton.ON. - When we call the
buttonOff()function, the value of the button will be set toButton.OFF. - When we call the
getButtonState()function, the value of the button will be returned.