Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Enum or int constants

Tags:

c#

I have a group of values that represent a state (ON, OFF, READY, ...). These values also get stored in a DB as an int field, so I am wondering if best practices would say to make this an enum or just bunch of const int types on a class.

Enum seems like a natural fit for human reading/coding, but it seems like it hides the fact that it matters which integers the values map to (or else values retrieved from a DB will be instantiated to the incorrect state). Someone may come in later and add a new value to the enum or something and throw the whole thing off.

Which is the better approach?

like image 283
Oxed Frederik Avatar asked May 15 '12 14:05

Oxed Frederik


2 Answers

I think enum is still the best choice for readability. However, since its values get stored in the DB, you should specify the values explicitly:

enum State { On = 1, Off = 2, Ready = 3};
like image 110
Sergey Kalinichenko Avatar answered Nov 02 '22 22:11

Sergey Kalinichenko


How is somebody adding a new enum value any different than a new constant int?

Remember, you can set an enum to a specific integer value.

Embrace readability!

As an added bonus, you can now use strong typing to prevent shenanigans like

Widget.state = 474;

Where 474 does not correspond to a state in your database.

like image 36
MushinNoShin Avatar answered Nov 02 '22 23:11

MushinNoShin