tags:

views:

542

answers:

7

In my project i'm using enums example:

public enum NcStepType { Start = 1, Stop = 3, Normal = 2 }

i'm reading values from a database, but sometimes there are 0-values in my record, so i want an enum that looks like

public enum NcStepType { Start = 1 OR 0, Stop = 3, Normal = 2 }

is this possible (in c#) ?

+2  A: 

No, basically. You would have to give it one of the values (presumably the 1), and interpret the other (0) manually.

Marc Gravell
+2  A: 

No it is not, and I'm not sure how it would work in practice.

Can't you just add logic that maps 0 to 1 when reading from the DB?

Mattias S
that's what i do right now, but it would be easier if i don't need to check if it's a valid value in my enum list. i'm working with a wcf service and when i'm trying to add the 0 value to my enum, it's always give me an Not Found Error
+1  A: 

No, in C# an enum can have only one value.

There's nothing that says the value in the database must map directly to your enum value however. You could very easily assign a value of Start whenever you read 0 or 1 from the database.

Nader Shirazie
A: 

No solution in C#. But you can take 2 steps:

1. Set default value of your DB field to 1.
2. Update all existing 0 to 1.

Ramesh Soni
+2  A: 

Normally i define in such cases the 0 as follows:

public enum NcStepType
{
    NotDefined = 0,
    Start = 1,
    Normal = 2,
    Stop = 3,
}

And somewhere in code i would make an:

if(Step == NcStepType.NotDefined)
{
    Step = NcStepType.Start;
}

This makes the code readable and everyone knows what happens... (hopefully)

Oliver
+1  A: 

You could create a generic extension method that handles unknown values:

    public static T ToEnum<T>(this int value, T defaultValue)
    {
        if (Enum.IsDefined(typeof (T),value))
            return (T) (object) value;
        else
            return defaultValue;
    }

Then you can simply call:

int value = ...; // value to be read

NcStepType stepType = value.ToEnum(NcStepType.Start);

// if value is defined in the enum, the corresponding enum value will be returned
// if value is not found, the default is returned (NcStepType.Start)
Philippe Leybaert
To make the function more self-explanatory i would call it ToEnumOrDefault() (like already existing linq extensions)
Oliver
A: 

As far as I know you can write this

enum NcStepType { Start = 0, Start = 1, Stop = 3, Normal = 2 }

The only problem is later there would be no way telling which Start was used for variable initialization (it would always look like it was the Start = 0 one).

zzandy
I would take Oliver's advice.
zzandy