Index

Solidity

  1. types
  2. External
  3. Library
    1. self in Library
    2. using * for
    3. self example
  4. interfaces
  5. import
  6. msg.value
  7. Handling ether
  8. Erc20 token in contract
  9. assembly
  10. Enum
  11. memory, storage, calldata
  12. Array Pushing
  13. length in array
  14. Struct array
  15. mapping
  16. bytes and string
  17. uint to bytes32
  18. returns with name
  19. score voting
  20. Tests
    1. Async Tests
    2. Hooks

Enum

Enums




Enums are one way to create a user-defined type in Solidity. They are explicitly convertible to and from all integer types but implicit conversion is not allowed. The explicit conversion from integer checks at runtime that the value lies inside the range of the enum and causes a failing assert otherwise. Enums require at least one member, and its default value when declared is the first member.
The data representation is the same as for enums in C: The options are represented by subsequent unsigned integer values starting from 0.


pragma solidity >=0.4.16 <0.7.0;

contract test {
    enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
    ActionChoices choice;
    ActionChoices constant defaultChoice = ActionChoices.GoStraight;

    function setGoStraight() public {
        choice = ActionChoices.GoStraight;
    }

    // Since enum types are not part of the ABI, the signature of "getChoice"
    // will automatically be changed to "getChoice() returns (uint8)"
    // for all matters external to Solidity. The integer type used is just
    // large enough to hold all enum values, i.e. if you have more than 256 values,
    // `uint16` will be used and so on.
    function getChoice() public view returns (ActionChoices) {
        return choice;
    }

    function getDefaultChoice() public pure returns (uint) {
        return uint(defaultChoice);
    }
}

Note
Enums can also be declared on the file level, outside of contract or library definitions.