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.
"A".ToEnum<Letters>();would be just fine. That being said, I think it may not be possible (not sure whether dynamics in C# 4 make it possible). If you could explain why you're trying to do this, there may be a better approach to the problem.as Enumnow. I think that will work. The console appeared to work, just seeing how my software will handle it.Enum.Parse(t, @string) as Enum;not accomplish the same thing?