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.
Enum.Parse(t, @string) as Enum;
That accomplishes the same thing as the solution you posted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With