Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum addition vs subtraction and casting

People also ask

What are the advantages of using an enum over an INT?

The advantages of using enums are that they are very easy to use and represented as strings but processed as integers. Enums are easy to maintain and improve code readability because they provide symbolic named constants, which means you need to remember the names, not the integer values.

Do enums have to be sequential?

There is nothing that requires them to be sequential. Your enum definition is fine and will compile without issue.

What are the parts of an enum called?

In computer programming, an enumerated type (also called enumeration, enum, or factor in the R programming language, and a categorical variable in statistics) is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type.

Can you add values to enum?

You can add a new value to a column of data type enum using ALTER MODIFY command. If you want the existing value of enum, then you need to manually write the existing enum value at the time of adding a new value to column of data type enum.


Good question - I was surprised that the first and third lines worked.

However, they are supported in the C# language specification - in section 7.8.4, it talks about enumeration addition:

Every enumeration type implicitly provides the following pre-defined operators, where E is the enum type and U is the underlying type of E:

E operator +(E x, U y)
E operator +(U x, E y)

At runtime, these operators are ealuated exactly as (E)((U)x + (U)y)

And in section 7.8.5:

Every enumeration type implicitly provides the following predefined operator, where E is the enum type and U is the underlying type of E:

U operator -(E x, E y)

This operator is evaluated exactly as (U)((U)x - (U)y)). In other words, the operator computes the difference between the ordinal values of x and y, and the type of the result is the underlying type of the enumeration.

E operator -(E x, U y);

This operator is evaluated exactly as (E)((U)x - y). In other words, the operator subtracts a value from the underlying type of the enumeration, yielding a value of the enumeration.

So that's why the compiler behaves like that - because it's what the C# spec says to do :)

I wasn't aware that any of these operators exist, and I've never knowingly seen them used. I suspect the reasons for their existence are buried somewhere in the language design meeting notes that Eric Lippert occasionally dives into - but I also wouldn't be surprised if they were regretted as adding features for little benefit. Then again, maybe they're really useful in some situations :)