Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This can be achieved using Expressions:</p> <pre><code>// requires object instance, but you can skip specifying T static string GetPropertyName&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; exp) { return (((MemberExpression)(exp.Body)).Member).Name; } // requires explicit specification of both object type and property type static string GetPropertyName&lt;TObject, TResult&gt;(Expression&lt;Func&lt;TObject, TResult&gt;&gt; exp) { // extract property name return (((MemberExpression)(exp.Body)).Member).Name; } // requires explicit specification of object type static string GetPropertyName&lt;TObject&gt;(Expression&lt;Func&lt;TObject, object&gt;&gt; exp) { var body = exp.Body; var convertExpression = body as UnaryExpression; if(convertExpression != null) { if(convertExpression.NodeType != ExpressionType.Convert) { throw new ArgumentException("Invalid property expression.", "exp"); } body = convertExpression.Operand; } return ((MemberExpression)body).Member.Name; } </code></pre> <p>Usage:</p> <pre><code>var x = new ObjectType(); // note that in this case we don't need to specify types of x and Property1 var propName1 = GetPropertyName(() =&gt; x.Property1); // assumes Property2 is an int property var propName2 = GetPropertyName&lt;ObjectType, int&gt;(y =&gt; y.Property2); // requires only object type var propName3 = GetPropertyName&lt;ObjectType&gt;(y =&gt; y.Property3); </code></pre> <p><strong>Update:</strong> fixed <code>GetPropertyName&lt;TObject&gt;(Expression&lt;Func&lt;TObject, object&gt;&gt; exp)</code> for properties returning value types.</p>
 

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