I have a class Bar that implements INotifyPropertyChanged. When setting the property CurrentFoo, I want to raise PropertyChanged if the value is changing. Foo implements IEquatable but not the == operator.
Currently my code looks like this:
public class Bar : INotifyPropertyChanged
{
// ...
private Foo fooValue;
/// <summary>
/// Gets or sets the active Foo
/// </summary>
/// <value>The active Foo.</value>
public Foo CurrentFoo
{
get
{
return this.fooValue;
}
set
{
// Notify listeners if value is changing.
if (null == this.fooValue && null != value
|| null != this.fooValue && null == value
|| null != this.fooValue && null != value && !this.fooValue.Equals(value))
{
this.fooValue = value;
this.OnPropertyChanged("CurrentFoo");
}
}
}
// ...
}
And it woks, but…ugleh! Is there a more elegant/best-practices way of doing this check without restoring to the Null object pattern (inconsistent with the rest of our codebase)?
I’ve considered writing a utility method like IsOneObjectNullButNotBoth(object a, object b)…but again, blah. Surely I’m missing a handy-dandy class library method, though I already checked those.
Testing one of the values for null is enough, because the Equals method should return false if the argument is null:
Alternatively, you can use the default EqualityComparer for Foo which checks for nulls and calls the Equals method: