Search code examples
c#.netreflectionenumsnullable

Parse to Nullable Enum


I am trying to parse a string back to a nullable property of type MyEnum.

public MyEnum? MyEnumProperty { get; set; }

I am getting an error on line:

Enum result = Enum.Parse(t, "One") as Enum;
// Type provided must be an Enum. Parameter name: enumType

I have a sample console test below. The code works if I remove nullable on the property MyEntity.MyEnumProperty.

How can I get the code to work without knowing the typeOf enum except via reflection?

static void Main(string[] args)
    {
        MyEntity e = new MyEntity();
        Type type = e.GetType();
        PropertyInfo myEnumPropertyInfo = type.GetProperty("MyEnumProperty");

        Type t = myEnumPropertyInfo.PropertyType;
        Enum result = Enum.Parse(t, "One") as Enum;

        Console.WriteLine("result != null : {0}", result != null);
        Console.ReadKey();
    }

    public class MyEntity
    {
        public MyEnum? MyEnumProperty { get; set; }
    }

    public enum MyEnum
    {
        One,
        Two
    }
}

Solution

  • Adding a special case for Nullable<T> will work:

    Type t = myEnumPropertyInfo.PropertyType;
    if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        t = t.GetGenericArguments().First();
    }