Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass compiler checked property names / Expression tree to a custom attribute
    primarykey
    data
    text
    <p>In a few places, I've noticed expression trees passed as arguments to methods to allow compiler checking of property names. For example, Caliburn Micro has the following method signature in its PropertyChangedBase class:</p> <pre><code>public virtual void NotifyOfPropertyChange&lt;TProperty&gt;(Expression&lt;Func&lt;TProperty&gt;&gt; property); </code></pre> <p>I have a custom attribute which I would like to have the same type of compiler checking of property names in the constructor, to enable me to type:</p> <pre><code>[MyCustomAttribute(() =&gt; PropertyName)] </code></pre> <p>Instead of:</p> <pre><code>[MyCustomAttribute("PropertyName")] </code></pre> <p>Using a constructor definition along the lines of:</p> <pre><code>public MyCustomAttribute(params Expression&lt;Func&lt;object&gt;&gt;[] properties) </code></pre> <p>However, due to the restriction on Attribute parameters being constant expressions, this appears not to be possible.</p> <p>Can anyone recommend a different approach where I can get the compiler to check property names in my attribute parameters rather than leaving this potential bug where only strings are used?</p> <p>Edit: Thanks to Marc's answer, I have implemented this for now:</p> <pre><code>#if DEBUG foreach (var propertyInfo in GetType().GetProperties().Where(propertyInfo =&gt; Attribute.IsDefined(propertyInfo, typeof (MyCustomAttribute)))) { foreach (var propertyName in propertyInfo.GetAttributes&lt;MyCustomAttribute&gt;(true) .SelectMany(attribute =&gt; attribute.PropertyNames)) Debug.Assert( GetType().GetProperty(propertyName) != null, "Property not found", "Property {0} declared on attributed property {1} was not found on type {2}.", propertyName, propertyInfo.Name, GetType().Name ); } #endif </code></pre>
    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. 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