I am trying to convert an object to an Enum I am getting through reflection and only have the Type information of it.
Here is my enum:
public enum Foo : int
{
Apple = 1,
Banana = 2,
Orange = 3,
}
Now in my method I am trying to set an object value, with the an enum the information I have is type info and an "original" value which is the int.
public class Bar
{
public Bar()
{
var enumValue = GetEnumValue(typeof(Foo), 0);
}
public object GetEnumValue(Type enumType, object value)
{
return Enum.ToObject(enumType, value);
}
}
This code is working so far but there is a "little" problem, you may have noticed that I am declaring fix values for my Foo Enum (Apple = 1, Banana = 2, Orange = 3) and in my GetEnumValue(typeof(Foo), 0) my second parameter is 0.
0 isn't a value specified in my Enum the Enum.ToObject() doesn't throw an exception or what ever it only works.
I would like to fix this so that if the GetEnumValue gets called with an invalid value the return value should be the default enum value.
Default enum value should be on a nullable enum null and on non-nullable the first enum so Apple in my case.