Solidity Enum Example

solidity enum example

Introduction

The word enum in solidity stands for Enumerable as it does in most of the other languages. Enum is a user defined data type which contains set of a predefined values called members of that enum.

The usage of enum in your code can result in reduction of bugs.

For example, consider an application for a fresh juice shop. It would be possible to restrict the glass size to small, medium, and large. This makes sure that it will not allow anyone to order any size other than small, medium, or large.

Code

pragma solidity ^0.5.0;

contract test {
   enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
   FreshJuiceSize choice;
   FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

   function setLarge() public {
      choice = FreshJuiceSize.LARGE;
   }

   function getChoice() public view returns (FreshJuiceSize) {
      return choice;
   }

}

Things to know about enum

Whenever you are using something that is new to you, one of the most important thing for you to remember is the limitation and rules. While using enum in solidity, you must keep in mind that it does not accept numbers, either positive or negative. Not even Boolean. But you can you TRUE/FALSE in capitalized form.

Another thing to remember is that you do not need to end the enum using semicolon, which we usually use in solidity for single declaration or instruction. Instead we will just use brackets for declaring the values of the enum.

Few other limitations of enum are that you cannot return enum within a function, as it is not included in ABI. You also cannot use enum in solidity if your compiler is less than 0.5.0