csdev
csdev

Reputation: 11

Tie enum to multiple integers

Lets say that i have this example enum:

public enum Enum
    {
        A,
        B
    }

Is it possible to tie it with multiple integers? Example: enum A will be tied to 1 and 2, enum B to 3 and 4.

Enum example = (Enum)1;
Console.WriteLine(example);
//A

example = (Enum)3;
Console.WriteLine(example);
//B

Edit

Dictionary is acceptable equivalent. Problem solved.

Upvotes: 0

Views: 94

Answers (2)

Flydog57
Flydog57

Reputation: 7111

This is what I was talking about in the comments (about using a [Flags] enum). Consider an enum that looks like:

[Flags]
public enum Days
{
    Sunday = 0x01, 
    Monday = 0x02, 
    Tuesday = 0x04, 
    Wednesday = 0x08, 
    Thursday = 0x10, 
    Friday = 0x20, 
    Saturday = 0x40, 
    Weekends = Sunday | Saturday, 
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday, 
    AllDays = Weekends | Weekdays
}

The days of the week entries each represent a single day. They are distinguished by a bit pattern that has exactly one bit set. The entries like Weekends, Weekdays and AllDays represent multiple values.

You can use them in functions like this:

public static bool IsWeekend(Days dayOfWeek)
{
    return (int)(dayOfWeek & Days.Weekends) != 0;
}

public static bool IsWeekday(Days dayOfWeek)
{
    return (int)(dayOfWeek & Days.Weekdays) != 0;
}

Both of those could be extension methods on the Days enumerated type if you'd like.

You can also get fancier like this:

public static IEnumerable<string> GetWeekdays()
{
    var allDays = (Days[])Enum.GetValues(typeof(Days));
    foreach (var day in allDays)
    {
        if (IsWeekday(day) && IsOnlyOneBitSet(day))
        {
            yield return day.ToString();
        }
    }
}

But you need a helper function like this (to make sure you only consider single day entries in the output, not the combined entries (like Weekdays):

private static bool IsOnlyOneBitSet(Days dayOfWeek)
{
    var asInt = (int) dayOfWeek;
    return asInt != 0 && (asInt & (asInt - 1)) == 0;
}

I'm not sure that this is what you are looking for, but I figure it might help you out.

If you call the GetWeekdays function, you get a collection that looks like this in the debugger:

    [0] "Monday"    string
    [1] "Tuesday"   string
    [2] "Wednesday" string
    [3] "Thursday"  string
    [4] "Friday"    string

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1064324

No, not natively as part of the language. An enum member is an alias to a single integer value. Multiple enum members can be aliases for the same numeric value (so you can have D = 1 and F = 1), but one alias is only one number.

You could use some other mechanism (attributes, or a simple lookup function) to do this yourself. But at that point, it probably isn't really an "enum" in the language sense, so it might be better to just use an integer.

Upvotes: 2

Related Questions