1

Can we convert Enum Value to string in Solidity? Which is more efficient to use in terms of GAS, ENums or CONST ?

1 Answer 1

6

Under the hood, enums are integers -- not strings. The compiler automatically picks the smallest possible integer value given the number of options, so that will almost always work out to less space, especially if your values are long.

Within your smart contract, Solidity will automatically handle converting names to ints for you. If you declare an enum like:

enum Colors {Red, Orange, Yellow, Green, Blue, Purple}

then elsewhere in the contract you could refer to Colors.Red and not have to worry about it actually being a 0 in memory. You could have 256 options in an enum and it'll still be stored as a uint8, whereas creating a string for each of those would allocate a dynamic byte array which is 32-bytes minimum. Punchline: use enums inside of your smart contracts.

If you're writing a front-end app which talks to the contract using web3, just create a mapping object in JS. Something like:

const colorEnum = { 0 : 'red', 1 : 'orange', 2 : 'yellow', 3 : 'green', 4 : 'blue', 5 : 'purple' }

3
  • thanks for the answer. My requirement is to pass a string to some method. Thats why I want to convert the value of enum to string. Please suugemt me if there is any way or better alternative than enum.
    – Amit Modi
    Aug 30, 2018 at 22:36
  • Is another smart contract passing the string, or an external application? If it's a JS app, you could use an object like colorEnum, but with the keys and values swapped.
    – ohsully
    Aug 31, 2018 at 11:39
  • another smart contract is acception strings.
    – Amit Modi
    Sep 1, 2018 at 2:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.