Enum initialization

Asked

Viewed 46 times

2

I’ve always created enums thus:

public enum TipoTelefone
{
  Residencial,
  Celular,
  Comercial
}

But today giving maintenance on a code I found one like this:

public enum TipoTelefone
{
    Residencial = 0,
    Celular,
    Comercial
}

What’s the difference of initializing the first element of enum?

2 answers

4


By default, the associated value of enumeration member constants is of the type int. The first variation starts at zero and is incremented by one for each following variant. Therefore, in this example:

enum TipoTelefone {
    Residencial,
    Celular,
    Comercial
}

The value for each variant is: Residencial, 0; Celular, 1 and Comercial, 2. Notice that it’s sequential.

But it is also possible to explicitly define values for members. For example:

enum ErrorCode {
    Residencial = 100,
    Celular = 200,
    Comercial = 300
}

In this case, members have explicitly defined values. There is no longer an implicit sequence in the above example. In the above example, it seems a little unnecessary, but it may be useful in some specific situations.

In cases as shown in the example of the question, in which only the first element is redefined, the others continue to follow its order, in a sequential way.

Then, in the example below, the definition of Residencial à 0 is redundant, since the first element is, by default, zero.

enum TipoTelefone {
    Residencial = 0,
    Celular,
    Comercial
}

But if you do something like:

enum TipoTelefone {
    Residencial = 5,
    Celular,
    Comercial
}

Variants shall be defined from 5. Residencial, 5; Celular, 6 and Comercial, 7.

3

This case changes nothing. It just adopted the more explicit style than the compiler already does by default. When nothing is informed the first value is always 0 and the others remains always the value of the previous member + 1.

It makes more sense when you want different default values.

And of course, if you have a very strange pattern, it’s best to be explicit at all to make it more readable. That is, opt for the implicit standard or be all explicit.

I particularly dislike the middle ground that is demonstrated, was explicit in one case and implied in the others.

There may always be case to adopt a mixture and even this case did not cause any major problem, but I prefer slightly more your way. Every case can act different, that’s just a trend. My advice is to avoid at most adopting different standards starting with 0 and each member will add 1 or else go in multiples, for example each member will go doubling in value, generally adopting the attribute [Flags]. but if the domain asks, it is okay to use other values. In some cases when it runs too far from the default maybe a enum is not the most appropriate. That’s the mechanism I see some abuse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.