Skip to main content

Command Palette

Search for a command to run...

Enum in Solidity

Published
2 min readView as Markdown
Enum in Solidity

Enum in Solidity

  1. In Solidity, an enum (short for enumeration) is a user-defined type that represents a set of named values.

  2. It is often used to define a list of possible options or choices that can be used as input or output for a contract function.

  3. An enum is defined using the enum keyword, followed by the name of the enum and the list of possible values, separated by commas and enclosed in curly braces. For example:

enum State { CREATED, IN_PROGRESS, COMPLETED }
  1. In this example, we've defined an enum called State that has three possible values: CREATED, IN_PROGRESS, and COMPLETED. Each value is assigned an integer value starting from 0, with CREATED being assigned the value of 0, IN_PROGRESS being assigned the value of 1, and COMPLETED being assigned the value of 2.

  2. Once an enum is defined, it can be used as a type for variables and function arguments. For example:

State public currentState;

function setState(State newState) public {
    currentState = newState;
}
  1. In this example, we've defined a public variable currentState of type State, which can hold one of the three possible values defined in the State enum. We've also defined a function setState that takes an argument newState of type State, which can be used to update the value of currentState.

  2. Using an enum can make your code more readable and maintainable by clearly indicating which values are valid inputs or outputs for a function or variable. It can also help catch errors at compile time by preventing invalid values from being used.