0 votes
by (2.0k points)

If I declare an enum like so : 

enum Colors
{
	Red, 
	Green, 
	Blue
}

Implicitly it has integer values given to it so behind the scenes, it looks like this : 

enum Colors
{
	Red = 0, 
	Green = 1, 
	Blue = 2
}

But I also know that I can manually give it integer values if I wanted to. For example : 

enum Colors
{
	Red = 1, 
	Green = 2, 
	Blue = 999
}

But when is this necessary? When should I bother giving an enum integer values myself?

1 Answer

0 votes
by (2.0k points)

In all honesty, for me, I give enums integer values 99 times out of 100. The main reasons for me to do are : 

- If the enum points to an integer value in the database (Either a lookup table OR simply stored as an integer on a table), then I don't want these values to ever change

- If the enum is ever represented as an integer anywhere else in my stack (For example does my API return enums as integers?)

They are kinda the same thing. Essentially, if my enum will ever be represented as an integer anywhere, then I never want that integer changing. Otherwise different parts of my system may have different ideas on what enum value maps to which integer. 

The reason for this is because any ordering of the enum itself will implicitly change the integer value if you haven't given it one. This is very easy to do accidentally. 

Mainly the times where I don't give the enum values is when I am using the enum ordering very specifically. For example : 

enum PriorityLevel
{
	Priority, 
	Regular
}

Items with a "Priority" value will be ranked (If ranking by their enum value) higher than regular. But if I do something like so : 

enum PriorityLevel
{
	FirstClass,
	Priority, 
	Regular
}

Then the ordering automatically still works without having to start going into negatives etc. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...