Mike
Mike

Reputation: 106

c# enum constants map to unique integer values

is there any way in c# to ensure enum constants map to unique integer values.

public enum Color
{
None =0,
red = 1,
blue= 2,
white = 3
}

Here if i do change numeric value of "white from 3 to 2" i should get the compilation error.

In my project i'm saving the enum integer value in DB respect to constant. i need a constraint in enum like if someone add a new constant in enum( e.g black). user must provide the unique numeric value with enum constant.

thanks

Upvotes: 0

Views: 1270

Answers (1)

Nick
Nick

Reputation: 25799

The best thing would be not to explicitly set the values in the enum definition. Put a comment in the enum definition telling anyone adding to it to ensure they only add to the end.

For example:

public enum Color
{
    None,
    red,
    blue,
    white,
    // **NEW ENTRIES MUST ONLY BE ADDED AT THE END OF THE ENUM**
}

Alternatively use the built-in Color structure and its ToArgb( ) method. Or indeed the KnownColor enumeration.

Upvotes: 3

Related Questions