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 #)?
+2
Jordy
source
to share
7 replies
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)
+2
source to share
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)
+2
source to share