HiveBrain v1.2.0
Get Started
← Back to all entries
principlecsharpMinor

Enum vs int wrapper struct

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enumwrapperintstruct

Problem

I am writing code that has objects having integer member variables where the integer value has a specific constant meaning, which normally means "use an enum".

Suppose the values are the days of the week, Monday = 0, Tuesday = 1, and so on. (In my real case, there are several different "types" involved, some of which have 10-20 possible values.)

The code uses data objects which are auto-generated, and these data objects can only have certain, already specified types (int, string, bool, double), otherwise they could just use enums themselves. The question is, should I use an enum, or a struct with static readonly definitions and implicit casting. I favor the struct version.

Here is an example of using an enum:

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


And here is my preferred struct code:

struct Day
{
    readonly int day;

    public Day(int day)
    {
        this.day = day;
    }
    public static implicit operator int(Day value)
    {
        return value.day;
    }
    public static implicit operator Day(int value)
    {
        return new Day(value);
    }

    public static readonly Day Monday = 0;
    public static readonly Day Tuesday = 1;
    public static readonly Day Wednesday = 2;
    public static readonly Day Thursday = 3;
    public static readonly Day Friday = 4;
    public static readonly Day Saturday = 5;
    public static readonly Day Sunday = 6;
}


My code frequently involves assigning values to the members of the data object. This means if I use the struct version, I can say for example Day myDay = dataObject.Day rather than Days myDay = (Days)dataObject.Day. With the amount of logic code that will be affected by this, I think the struct version is a win for readability because it removes a lot of explicit casts.

I don't want to just use plain ints in my code because I like function signatures that indicate the purpose of

Solution

Normally it would disgust me, but you appear to have a valid reason to use it, which stems from the pre-existing disgusting situation that you have to cope with these data objects that use ints.

The only thing I would ask is, why can these data objects not use enums? What is it about their auto-generation that precludes enums from being used? I do not think that enums receive any special handling at the IL level, they are handled just like primitive types are.

Context

StackExchange Code Review Q#7566, answer score: 4

Revisions (0)

No revisions yet.