C# Overloading Enums To Store Values

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!

Answers


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
    }
}

Need Your Help

How to run django-sentry on windows?

python django error-logging

I have an issue to run django-sentry on windows. I have read this issue github.com/dcramer/django-sentry/issues/245. I skipped 'python-daemon>=1.6' during manual installation of django-sentry. But ...

How can I ask the user for elevated permissions at runtime?

c++ windows qt

Some applications, started with a regular user will ask for elevated permissions when necessary (e.g. a file manager needs to write such folder), and then carry on with the operation.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.