Enums In Solidity

In this article, we will examine Solidity enums in depth, explaining their properties, use cases, and how to work with them effectively in smart contracts.

In enums, variables can only take one of the predefined values. In this enumerated list, the values are called enums.

Enum can help you minimize the number of defects in your code.

Consider, for instance, an application for a fresh juice shop where the glass size can be limited to small, medium, or large.

This would prevent anyone from ordering other sizes than small, medium, and large.

The given example will help you understand the working of solidity enums in an easier way:

Example: 

// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.8.0;contract SolidityTest { enum Juice_Glass_Sizes{SMALL,MEDIUM,LARGE}Juice_Glass_Sizes choice; Juice_Glass_Sizes constant DefaultChoice=Juice_Glass_Sizes.LARGE;function set_Choice_Small() public {choice=Juice_Glass_Sizes.SMALL; }function get_Choice_Small() public view returns(Juice_Glass_Sizes){ return choice; }function convert_choice_string_to_int() public pure returns(uint){return uint(DefaultChoice); }}
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>
The given example will make it easier for you to understand the working of enums in solidity:

Example: 

// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.8.0;contract SolidityTest { enum Sports{CRICKET,FOOTBALL,VOLLEYBALL,RUGBY,HOCKEY}Sports selection; Sports constant default_selection=Sports.RUGBY;function set_Selection() public {selection=Sports.VOLLEYBALL;}function get_Selection() public view returns(Sports){return selection;}function get_Default_Selection() public pure returns(Sports){return default_selection; }function string_to_Int_Conversion() public pure returns(uint){return uint(default_selection);}}
<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>

If you find Difficulty in executing the code above, have a look at the steps of executing the program from our article Write smart contract.

If we call the get_Default_Select function we get:

Solidity Enums examples

Similarly the output of the get_Selection function will be:

Solidity Enums example 2

 

 

Conclusion

Solidity Enums provides a useful feature for defining custom data types with a limited set of values.

They help make code more readable and maintainable by providing a clear definition of allowed values for a particular variable or parameter.

Enums can also be used in conjunction with other Solidity features, such as structs and mappings, to create more complex data structures.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *