Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

solidity
enum
communitycreator

What are enums in Solidity?

Shubham Singh Kshatriya

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 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;
  }
}
Creating an example enum

Explanation

  • Line 3: We create a contract named Example.
  • Line 5: We create an enum named Button.
  • Line 8: We declare a variable button of the enum type.
  • 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 to Button.ON.
  • When we call the buttonOff() function, the value of the button will be set to Button.OFF.
  • When we call the getButtonState() function, the value of the button will be returned.

RELATED TAGS

solidity
enum
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring