Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define an enumeration where multiple values map to a single label?

Suppose, for the sake of this example, that I am trying to parse a file which specifies that two arbitrary bytes in the record represent the day of the week, thusly:

DayOfWeek:

 - 0    = Monday
 - 1    = Tuesday
 - 2    = Wednesday
 - 3    = Thursday
 - 4    = Friday
 - 5    = Saturday
 - 6    = Sunday
 - 7-15 = Reserved for Future Use

I can define an enumeration to map to this field, thusly:

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
     ReservedForFutureUse
}

But how can I define valid values for ReservedForFutureUse? Ideally, I'd like to do something like:

public enum DaysOfWeek
    {
         Monday = 0,
         Tuesday = 1,
         Wednesday = 2,
         Thursday = 3,
         Friday = 4,
         Saturday = 5,
         Sunday = 6
         ReservedForFutureUse = {7,8,9,10,11,12,13,14,15}
    }

This problem is only exacerbated with more complicated fields; suppose, for example, that both 7 and 8, in this case, map to the same error case or something. How can one capture this requirement in a C# enumeration?

like image 402
GWLlosa Avatar asked Mar 11 '13 14:03

GWLlosa


2 Answers

One funny quirk with enums is that a variable defined as a certain enum type can hold values that are not defined by any member of that enum:

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
}

// in other code
DaysOfWeek someDay = (DaysOfWeek)42; // this is perfectly legal

This means that you don't really need to define all possible values that can appear, but can rather just specify those that mean something to your code. Then you can use some "catch-all" if- or switch-block to handle undefined values:

switch (someDay)
{
    case DaysOfWeek.Monday:
    {
        // do monday stuff
        break;
    }
    case DaysOfWeek.Tuesday:
    {
        // do tuesday stuff
        break;
    }
    // [...] handle the other weekdays [...]
    default:
    {
        // handle undefined values here
        break;
    }
}
like image 94
Fredrik Mörk Avatar answered Nov 01 '22 15:11

Fredrik Mörk


Although a given underlying value may be mapped to multiple enum values, an enum value can have exactly one underlying value.

You could just do this

public enum DaysOfWeek
{
     Monday = 0,
     Tuesday = 1,
     Wednesday = 2,
     Thursday = 3,
     Friday = 4,
     Saturday = 5,
     Sunday = 6
     Reserved1 = 7
     ...
     Reserved8 = 15
}
like image 34
p.s.w.g Avatar answered Nov 01 '22 17:11

p.s.w.g