Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>The nameof operator was implemented in C# 6.0 with .NET 4.6 and VS2015 in July 2015. The following is still valid for C# &lt; 6.0</h2> <p>To avoid strings which contain property names, I've written a simple class using expression trees to return the name of the member:</p> <pre><code>using System; using System.Linq.Expressions; using System.Reflection; public static class Member { private static string GetMemberName(Expression expression) { switch (expression.NodeType) { case ExpressionType.MemberAccess: var memberExpression = (MemberExpression) expression; var supername = GetMemberName(memberExpression.Expression); if (String.IsNullOrEmpty(supername)) return memberExpression.Member.Name; return String.Concat(supername, '.', memberExpression.Member.Name); case ExpressionType.Call: var callExpression = (MethodCallExpression) expression; return callExpression.Method.Name; case ExpressionType.Convert: var unaryExpression = (UnaryExpression) expression; return GetMemberName(unaryExpression.Operand); case ExpressionType.Parameter: return String.Empty; default: throw new ArgumentException("The expression is not a member access or method call expression"); } } public static string Name&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; expression) { return GetMemberName(expression.Body); } public static string Name&lt;T&gt;(Expression&lt;Action&lt;T&gt;&gt; expression) { return GetMemberName(expression.Body); } } </code></pre> <p>You can use this class as follows. Even though you can use it only in code (so not in XAML), it is quite helpful (at least for me), but your code is still not typesafe. You could extend the method Name with a second type argument which defines the return value of the function, which would constrain the type of the property.</p> <pre><code>var name = Member.Name&lt;MyClass&gt;(x =&gt; x.MyProperty); // name == "MyProperty" </code></pre> <p>Until now I haven't found anything which solves the databinding typesafety issue.</p> <p>Best Regards</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