Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and Cons explicitly setting enum field's values

Tags:

.net

theory

Is it preferable to explicitly set enum's fields instead of just defining their names? E.g. any pros and cons for Enum1 vs Enum2?

Enum1:

enum SomeEnum
{
   Something1 = 0,
   Something2 = 1
}

Enum2:

enum SomeEnum
{
   Something1,
   Something2
}

P.S. This question doesn't relates to enums that would be stored in database, which is requires to set values explicitly.

Edit: Say all values are 0, 1, etc... They are not negative or something.

like image 952
Kamarey Avatar asked Nov 05 '09 15:11

Kamarey


2 Answers

Enum1 and Enum2 compile to the same enumeration. So from a programming standpoint, there is no difference. From a maintenance standpoint, there may or may not be issues.

On the one hand, declaring explicit values is absolutely required for a [Flags] enum; and they need to be values at powers of 2.

On the other hand, explicit values can reduce maintainability simply by creating values that cannot or should not be changed in the future.

In general, I prefer to not declare explicit values unless the values themselves are significant for some reason -- if your C# enumeration is, for example, wrapping a C enumeration.

like image 89
Randolpho Avatar answered Sep 18 '22 15:09

Randolpho


it's useful when you need to have negative values

enum
{
  Error = -1,
  Success = 0,
  Something1, 
  Something2,
};
like image 26
Max Avatar answered Sep 20 '22 15:09

Max