1

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.

1 Answer 1

2

Instead of the constructor you have place this:

        public Bar(int value)
        {
            if (Enum.IsDefined(typeof(Foo), value))
            {
                var enumValue = GetEnumValue(typeof(Foo), value);
            }
            else
            {
                var enumValue = GetEnumValue(typeof(Foo), 1);

                //or like this...
                var enumValue1 = Enum.GetValues(typeof(Foo)).GetValue(0);
            }
        }

I left it very explicit so you get what is happening.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.