Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the getter is public, then the following should work. It will give you an extension method that looks like this:</p> <pre><code>var propertyName = myTestObject.NameOf(o =&gt; o.TestProperty); </code></pre> <p>It requires a public getter. I hope, at some point, reflection functionality like this is rolled into the language.</p> <pre><code>public static class Name { public static string Of(LambdaExpression selector) { if (selector == null) throw new ArgumentNullException("selector"); var mexp = selector.Body as MemberExpression; if (mexp == null) { var uexp = (selector.Body as UnaryExpression); if (uexp == null) throw new TargetException( "Cannot determine the name of a member using an expression because the expression provided cannot be converted to a '" + typeof(UnaryExpression).Name + "'." ); mexp = uexp.Operand as MemberExpression; } if (mexp == null) throw new TargetException( "Cannot determine the name of a member using an expression because the expression provided cannot be converted to a '" + typeof(MemberExpression).Name + "'." ); return mexp.Member.Name; } public static string Of&lt;TSource&gt;(Expression&lt;Func&lt;TSource, object&gt;&gt; selector) { return Of&lt;TSource, object&gt;(selector); } public static string Of&lt;TSource, TResult&gt;(Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector) { return Of(selector as LambdaExpression); } } public static class NameExtensions { public static string NameOf&lt;TSource, TResult&gt;(this TSource obj, Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector) { return Name.Of(selector); } } </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