Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to Enum using type variable

Part of my software is using reflection. The issue I am having is that while I can get the type of the property, I cannot convert the string value using the Type from the PropertyInfo. This is the reason why i am using t in the sample code.

The below code demonstrates the issue with the error message as a code comment. The syntax error is on the t. how can I fix this problem? thanks

class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(Letters);

        Letters letter = "A".ToEnum<t>(); //-- Type or namespace expected.
    }
}

public enum Letters { A, B, C }

//-- This is a copy of the EmunHelper functions from our tools library.
public static class EnumExt
{
    public static T ToEnum<T>(this string @string)
    {
        int tryInt;
        if (Int32.TryParse(@string, out tryInt)) return tryInt.ToEnum<T>();
        return (T)Enum.Parse(typeof(T), @string);
    }
    public static T ToEnum<T>(this int @int)
    {
        return (T)Enum.ToObject(typeof(T), @int);
    }
}

Solution:

The following works because when the value is set using reflection, the actual type of Enum is accepted. Where myObject.Letter = result is not.

Type t = currentProperty.PropertyType;
Enum result = Enum.Parse(t, @string) as Enum;
ReflectionHelper.SetProperty(entity, "LetterPropertyName", result);

Thank you all for your help.

like image 202
Valamas Avatar asked Aug 31 '25 16:08

Valamas


1 Answers

Enum.Parse(t, @string) as Enum;

That accomplishes the same thing as the solution you posted.

like image 123
Kevin Stricker Avatar answered Sep 03 '25 18:09

Kevin Stricker