I have an enum with a bunch of values that looks like this. Notice that I use 0 for "undefined".
public enum MyEnum
{
Apple = 1,
Banana = 2,
Orange = 3,
Undefined = 0
}
I want to create a conversion method that will receive an int value and return enum but I want to make sure that if a value that is NOT in my enum is received, I return "Undefined". I have the following code but if I pass 47, I want to make sure I get MyEnum.Undefined. How should I modify this code so that any undefined value returns MyEnum.Undefined.
public static MyEnum GetEnum(int value)
{
var enumValue = MyEnum.Undefined;
if(value > 0)
enumValue = (MyEnum)value;
return enumValue;
}
Just use Enum.IsDefined
:
public static MyEnum GetEnum(int value) =>
Enum.IsDefined(typeof(MyEnum), value) ? (MyEnum) value : MyEnum.Undefined;
Complete example:
using System;
public enum MyEnum
{
// Moved here as it's more conventional.
Undefined = 0,
Apple = 1,
Banana = 2,
Orange = 3
}
class Test
{
public static void Main()
{
Console.WriteLine(GetEnum(5)); // Undefined
Console.WriteLine(GetEnum(0)); // Undefined
Console.WriteLine(GetEnum(-1)); // Undefined
Console.WriteLine(GetEnum(3)); // Orange
}
public static MyEnum GetEnum(int value) =>
Enum.IsDefined(typeof(MyEnum), value) ? (MyEnum) value : MyEnum.Undefined;
}
See more on this question at Stackoverflow