I’m looking for an easy way to enforce the correct implementation of INotifyPropertyChanged i.e. when PropertyChanged is raised it must reference a property that is actually defined. I tried doing this with the new CodeContract tools from Microsoft, but I keep getting the warning “CodeContracts: requires unproven”. Here is my code…
public sealed class MyClass : INotifyPropertyChanged
{
private int myProperty;
public int MyProperty
{
get
{
return myProperty;
}
set
{
if (myProperty == value)
{
return;
}
myProperty = value;
OnPropertyChanged("MyProperty");
}
}
private void OnPropertyChanged(string propertyName)
{
Contract.Requires(GetType().GetProperties().Any(x => x.Name == propertyName));
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Is there anyway to get this to work?
I assume you mean with the static analysis tools? (I would expect the runtime check to work, at least – and you could presumably leave it in debug builds). I doubt that this is something that static analysis is going to be able to see through –
GetType().GetProperties()is simply too complex, etc.In short; I doubt it… lambdas (
Expression) are an option, but they are much slower than passing just a string.