DEV Community

Cover image for Day 12 - Enums
Vedant Chainani
Vedant Chainani

Posted on • Edited on

4 1

Day 12 - Enums

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 12 of 30 in Solidity Series
Today I Learned About Enums in Solidity.

Enums are the way of creating user-defined data types, it is usually used to provide names for integral constants which makes the contract better for maintenance and reading.

Enums restrict the variable with one of a few predefined values, these values of the enumerated list are called enums. Options are represented with integer values starting from zero, a default value can also be given for the enum. By using enums it is possible to reduce the bugs in the code.

Syntax

enum <enumerator_name> { 
    element 1, 
    element 2,
    ....,
    element n
} 
Enter fullscreen mode Exit fullscreen mode

Example:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract EnumType {
    // Creating an enumerator
    enum Days {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
    // Declaring variables of type enumerator
    Days day;

    // Setting a default value
    Days constant defaultDay = Days.Monday;

    // Get default Day
    function getDefaultDay() public pure returns (Days) {
        return defaultDay;
    }

    // Set day to a object from the enumerator Days
    function setDay() public {
        day = Days.Tuesday;
    }

    // get value of day
    function getDay() public view returns (Days) {
        return day;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

When we run the getDefaultDay function, we get the default value of the enumerator.

0:uint8: 0
Enter fullscreen mode Exit fullscreen mode

When we run the getDay function we get 0:uint8: 0 as we have set it to a default value of Monday.

When we run the setDay function and then run the getDay function we get 0:uint8: 1 as setDay function has set the value of day to Tuesday.


Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay