Solidity Tutorial

Learn Enum in Solidity (Enumerated Types)

Share on twitter
Share on linkedin
Share on whatsapp
Share on facebook
Share on telegram

Contents

What is Enum in Solidity

In Solidity, Enum is a kind of custom data type that is useful to work with integer constants by assigning them a name. Assume your business logic deals with three types of customers – Regular, Premium, and VIP. We can create an enum data type Customer_Type and assign the three customer types to it as shown below.

enum customerType{Regular, Premium, VIP}

 

Internally, Solidity assigns numeric values starting from 0 from left to right. This means Regular, Premium, and VIP are assigned 0, 1, and 2 respectively. Since enum is a data type you can create its variable.

Although you can work without Enums but they are useful for readability and maintainability of the code base.

Example of Enum in Solidity

In the below example, a variable cust is declared of enum data type customerType and is initialized with the ‘VIP’ member of the enum.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract DemoContract 
{
    enum customerType{Regular, Premium, VIP}

    customerType cust = customerType.VIP;
   
}

 

Expanding our example further, the constant member of enum can be used throughout the code for various purposes.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract DemoContract 
{
    enum customerType{Regular, Premium, VIP}

    customerType cust = customerType.VIP;

    uint public discount;

   function calculate_discount() public 
    {      
        if (cust == customerType.Regular)
        {
            discount = 15;          
        }
        else if (cust == customerType.Premium)
        {
            discount = 25;          
        }
        else if (cust == customerType.VIP)
        {
            discount = 35;          
        }
    }
}

 

To access the first and last element of the enum you can use type(NameOfEnum).min and type(NameOfEnum).max respectively. Below is the example of its usage. Variable cust1 is assigned customerType.Regular and cust2 is assigned customerType.VIP as value.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

contract DemoContract 
{
    enum customerType{Regular, Premium, VIP}

    customerType cust1 = type(customerType).min;

    customerType cust2 = type(customerType).max;

}

 

Other Points to Consider

  • You cannot have more than 256 members inside an enum in Solidity 0.8.0 and above. Before that, it could have more than 256 members.
  • Atlease one member is required in the enum and the first member becomes the default value.
  • The members inside the enum cannot be an integer or Boolean value.
  • Enums can be declared at the file level, outside of the contract.
  • Enums are not supported by ABI, so if the enum is used as a return type inside the function it is represented as uint8 for all purposes external to Solidity.