Enumeration name with multiple values
In my project I am using an example of enums:
public enum NcStepType { Start = 1, Stop = 3, Normal = 2 }
I am reading values ββfrom the database, but sometimes there are 0-values ββin my entry, so I want an enum that looks like
public enum NcStepType { Start = 1 OR 0, Stop = 3, Normal = 2 }
is this possible (in C #)?
You can 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)
No, basically. You would have to give it one of the values ββ(presumably 1) and interpret the other (0) manually.
No, it doesn't, and I'm not sure how this would work in practice.
Can't you just add logic that maps from 0 to 1 when reading from the DB?
I usually define 0 in such cases as follows:
public enum NcStepType
{
NotDefined = 0,
Start = 1,
Normal = 2,
Stop = 3,
}
And somewhere in the code I would do:
if(Step == NcStepType.NotDefined)
{
Step = NcStepType.Start;
}
This makes the code readable and everyone knows what's going on ... (hopefully)
No, in C #, an enum can only have one value.
There is nothing that says that the value in the database should map directly to your enum value. You can easily assign a value Start
whenever you read 0
or 1
from the database.
There is no solution in C #. But you can do 2 steps:
1. Set the default value for your DB field to 1.
2. Update any existing 0s to 1.
As far as I know you can write this
enum NcStepType { Start = 0, Start = 1, Stop = 3, Normal = 2 }
The only problem is that later there would be no way to specify which one Start
was used to initialize the variable (it would always look like Start = 0
).