Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Enum as/with expressions?
    text
    copied!<p>Is it possible to use an enum with expressions to reflect on the enum values? Consider this <em>hypothetical</em> routine:</p> <pre><code>public enum Fruit { Apple, Pear } public void Foo(Fruit fruit) { Foo&lt;Fruit&gt;(() =&gt; fruit); } public void Foo&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expression) { //... example: work with Fruit.Pear and reflect on it } </code></pre> <p><code>Bar()</code> will give me information about the enum, but I want to work with the actual value.</p> <p>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.</p> <p>I'm fully aware you can work with the enum type to get the CustomAttributes that way.</p> <p><strong>Update:</strong></p> <p>I use a similar concept in MVC with helper extensions:</p> <pre><code>public class HtmlHelper&lt;TModel&gt; : System.Web.Mvc.HtmlHelper&lt;TModel&gt; { public void BeginLabelFor&lt;TProperty&gt;(Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression) { string name = ExpressionHelper.GetExpressionText(expression); } } </code></pre> <p>In this example <code>name</code> 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?</p> <p><strong>Updated example:</strong></p> <pre><code>public enum Fruit { [Description("I am a pear")] Pear } public void ARoutine(Fruit fruit) { GetEnumDescription(() =&gt; fruit); // returns "I am a pear" } public string GetEnumDescription&lt;T&gt;(/* what would this be in a form of expression? Expression&lt;T&gt;? */) { MemberInfo memberInfo; // a routine to get the MemberInfo(?) 'Pear' from Fruit - is this even possible? if (memberInfo != null) { return memberInfo.GetCustomAttribute&lt;DescriptionAttribute&gt;().Description; } return null; // not found or no description } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload