Is it possible to use an enum with expressions to reflect on the enum values? Consider this hypothetical routine:
public enum Fruit
{
Apple,
Pear
}
public void Foo(Fruit fruit)
{
Foo<Fruit>(() => fruit);
}
public void Foo<T>(Expression<Func<T>> expression)
{
//... example: work with Fruit.Pear and reflect on it
}
Bar()
will give me information about the enum, but I want to work with the actual value.
Background: I've been adding some helper methods to return CustomAttribute information for types and wondered if a similar routine could be used for enums.
I'm fully aware you can work with the enum type to get the CustomAttributes that way.
Update:
I use a similar concept in MVC with helper extensions:
public class HtmlHelper<TModel> : System.Web.Mvc.HtmlHelper<TModel>
{
public void BeginLabelFor<TProperty>(Expression<Func<TModel, TProperty>> expression)
{
string name = ExpressionHelper.GetExpressionText(expression);
}
}
In this example name
would be the member name of the model. I want to do a similar thing with enums, so name would be the enum 'member'. Is this even possible?
Updated example:
public enum Fruit
{
[Description("I am a pear")]
Pear
}
public void ARoutine(Fruit fruit)
{
GetEnumDescription(() => fruit); // returns "I am a pear"
}
public string GetEnumDescription<T>(/* what would this be in a form of expression? Expression<T>? */)
{
MemberInfo memberInfo;
// a routine to get the MemberInfo(?) 'Pear' from Fruit - is this even possible?
if (memberInfo != null)
{
return memberInfo.GetCustomAttribute<DescriptionAttribute>().Description;
}
return null; // not found or no description
}