Question

I currently have an enum defined as follows:

public enum ColorEnum { Red, White, Blue, Green };

Each of these enum values has an underlying int value that I need to be able to return to the user. To do so, I wrote a function that takes in the enum and returns an int:

public int colorToValue(ColorEnum color)
{
    switch (color)
    {
        case Red:
            return 5;
        case White:
            return 10;
        case Blue:
            return 15;
        case Green:
            return 20;
    }

    return 0;
}

This works well and good but I was wondering if I could simplify things by using the enum itself to store the underlying values. For example, could I just define the enum as follows:

public enum ColorEnum { Red = 5, White = 10, Blue = 15, Green = 20 };

Then converting the enum to it's underlying value would be as simple as casting it to an int. The above function simplifies to the following:

public int colorToValue(ColorEnum color)
{
    return (int)color;
}

Of course, the values for each enum entry would have to be an int as required by the enum definition.

Thanks!

Was it helpful?

Solution

Yes that is entirely valid and will work fine. Enums cast cleanly to/from their underlying type, and it is very common for them to have prescribed values rather than just 1,2,3...

The only thing to watch, though, is that the reverse is true too. So this works fine:

ColorEnum evil = (ColorEnum)(-53); // why not...

Your original colorToValue(evil) code would return 0 for this; your new code will return -53. Personally I might have thrown an ArgumentOutOfRangeException.

There is also an Enum.IsDefined method, but that involves boxing the value. But if you do want to check the input is an expected value, at least you can simplify:

public int colorToValue(ColorEnum color)
{
    switch (color)
    {
        case Red:
        case White:
        case Blue:
        case Green:
            return (int)color;
        default:
            return 0; // or throw, whatever
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top