2

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#) ?

8 Answers 8

2

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

To make the function more self-explanatory i would call it ToEnumOrDefault() (like already existing linq extensions)
2

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

Comments

2

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?

1 Comment

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
2

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)

Comments

1

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.

Comments

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

1 Comment

Please provide some explanation why do you think your proposed solution might the OP. Please share with us description as well not just code.
0

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.

Comments

0

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).

1 Comment

I would take Oliver's advice.