0
0
Blockchain / Solidityprogramming~5 mins

Enums in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Enums help you give names to a set of related values. This makes your code easier to read and less error-prone.

When you want to represent a fixed set of options, like days of the week.
When you need to track states, such as order status in a shopping app.
When you want to make your code clearer by using names instead of numbers.
When you want to prevent invalid values by limiting choices.
When you want to improve code readability and maintenance.
Syntax
Blockchain / Solidity
enum EnumName {
    OPTION1,
    OPTION2,
    OPTION3
}

Enums group related constants under one name.

Each option inside an enum is a named value.

Examples
This enum defines three colors: RED, GREEN, and BLUE.
Blockchain / Solidity
enum Color {
    RED,
    GREEN,
    BLUE
}
This enum represents order statuses.
Blockchain / Solidity
enum Status {
    PENDING,
    SHIPPED,
    DELIVERED
}
Sample Program

This smart contract uses an enum to track the status of an order. It starts as Pending, then can be changed to Shipped or Delivered. The getStatus function returns the current status as a word.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract Order {
    enum Status { Pending, Shipped, Delivered }

    Status public orderStatus;

    constructor() {
        orderStatus = Status.Pending;
    }

    function shipOrder() public {
        orderStatus = Status.Shipped;
    }

    function deliverOrder() public {
        orderStatus = Status.Delivered;
    }

    function getStatus() public view returns (string memory) {
        if (orderStatus == Status.Pending) {
            return "Pending";
        } else if (orderStatus == Status.Shipped) {
            return "Shipped";
        } else {
            return "Delivered";
        }
    }
}
OutputSuccess
Important Notes

Enums in blockchain smart contracts help keep track of states clearly.

Each enum option is stored as a number starting from 0 internally.

Use enums to avoid mistakes from using plain numbers or strings.

Summary

Enums group related named values for clarity.

They help track states or fixed options safely.

Using enums makes your code easier to read and maintain.