Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ok, first of all, for this purpose I personally use ObservableObject implementation from the <a href="http://mvvmfoundation.codeplex.com/" rel="nofollow noreferrer">MVVM foundation</a>. It is a DEBUG-build only runtime check almost identical to yours.</p> <pre><code>public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { this.VerifyPropertyName(propertyName); PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } [Conditional("DEBUG")] [DebuggerStepThrough] public void VerifyPropertyName(string propertyName) { // Verify that the property name matches a real, // public, instance property on this object. if (TypeDescriptor.GetProperties(this)[propertyName] == null) { string msg = "Invalid property name: " + propertyName; if (this.ThrowOnInvalidPropertyName) throw new Exception(msg); else Debug.Fail(msg); } } </code></pre> <p>It's probably the easiest way, but it has certain disadvantages: you need to be able to inherit from some base class, it only works in runtime (though this was always enough in my wpf-experience), it surely looks like a "patch" for a missing static check.</p> <p>You have several ways to enable static analysis / static tools for this case:</p> <ol> <li>Like Marc says, <a href="http://blog.m.jedynak.pl/2009/02/static-typed-propety-names.html" rel="nofollow noreferrer">use lambda notation and extract string in run-time</a>.</li> <li><a href="http://www.binarycoder.net/fxcop/html/index.html" rel="nofollow noreferrer">Write a custom FxCop rule</a>. </li> <li><a href="http://geekswithblogs.net/thomasweller/archive/2009/09/15/aop-can-save-you-tons-of-repetitive-code.aspx" rel="nofollow noreferrer">Use an AOP tool to post-process code</a> with some meta-markup.</li> </ol> <p>As for the CodeContracts, I believe it is not yet mature enough to handle this kind of checks in static analysis. Imagine, it has to parse your lambda, understand how it can be failed by a wrong <code>propertyName</code>, find all calls to this method, figure out all possible inputs, etc. It is just a wrong instrument for that kind of check.</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