Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 420
Valamas Avatar asked Mar 19 '12 01:03

Valamas


People also ask

What is enum parse in c#?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.

What does enum TryParse do?

TryParse(Type, String, Object)Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Is enum parse case-sensitive?

Method 2: Enum. Just like the previous method, this method is also case-sensitive by default but can be configured to be case-insensitive.

Can enum have NULL values?

An ENUM can also contain NULL and empty values. If the ENUM column is declared to permit NULL values, NULL becomes a valid value, as well as the default value (see below).


2 Answers

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

Type t = myEnumPropertyInfo.PropertyType;
if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    t = t.GetGenericArguments().First();
}
like image 84
Matt Hamilton Avatar answered Sep 28 '22 06:09

Matt Hamilton


Here you go. A string extension that will help you with this.

    /// <summary>
    /// <para>More convenient than using T.TryParse(string, out T). 
    /// Works with primitive types, structs, and enums.
    /// Tries to parse the string to an instance of the type specified.
    /// If the input cannot be parsed, null will be returned.
    /// </para>
    /// <para>
    /// If the value of the caller is null, null will be returned.
    /// So if you have "string s = null;" and then you try "s.ToNullable...",
    /// null will be returned. No null exception will be thrown. 
    /// </para>
    /// <author>Contributed by Taylor Love (Pangamma)</author>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="p_self"></param>
    /// <returns></returns>
    public static T? ToNullable<T>(this string p_self) where T : struct
    {
        if (!string.IsNullOrEmpty(p_self))
        {
            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
            if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
        }

        return null;
    }

https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions

like image 40
Pangamma Avatar answered Sep 28 '22 06:09

Pangamma