Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use expressions for this. The usage would look like this:</p> <pre><code>Magic_GetName&lt;Foo&gt;(x =&gt; x.Bar) </code></pre> <p>The implementation of <code>Magic_GetName</code> would look like this:</p> <pre><code>public static string Magic_GetName&lt;TClass&gt;( Expression&lt;Func&lt;TClass, object&gt;&gt; propertyExpression) { propertyExpression.Dump(); var body = propertyExpression.Body as UnaryExpression; if (body == null) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "The body of the 'propertyExpression' should be an " + "unary expression, but it is a {0}", propertyExpression.Body.GetType())); } var memberExpression = body.Operand as MemberExpression; if (memberExpression == null) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "The operand of the body of 'propertyExpression' should " + "be a member expression, but it is a {0}", propertyExpression.Body.GetType())); } var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "The member used in the expression should be a property, " + "but it is a {0}", memberExpression.Member.GetType())); } return propertyInfo.Name; } </code></pre> <p><strong>Update:</strong> The title of this question is "Getting property names at <strong>compile</strong> time".<br> My answer actually doesn't do that. The method <code>Magic_GetName</code> is executed at <em>runtime</em> and as such has a performance impact.</p> <p>The .NET 4.5 way using <a href="http://danrigby.com/2012/03/01/inotifypropertychanged-the-net-4-5-way/" rel="noreferrer">the <code>CallerMemberName</code> attribute</a> on the other hand is really <a href="http://rohiton.net/2012/03/05/caller-information/" rel="noreferrer">a compile time feature</a> and as such doesn't have a runtime impact. However, as I already said in the comments, it is not applicable in the given scenario.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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