There are some things to be aware of when using this inteface in WPF. When overriding the Equals method from the base Object, the samples show comparing the obj parameter to null, otherwise it attempts to cast to the typed object and call the typed Equals implmentation. eg.
if (obj == null) return base.Equals(obj);
if (!(obj is Currency))
throw new InvalidCastException("The 'obj' argument is not a Currency object.");
return Equals(obj as Currency);
However, if using the object in WPF, especially in a binding scenario, it is possible that obj will be DependencyProperty.UnsetValue. It will therefore fail the null check, but is not of type Currency (the generic type defined), and will therefore raise the InvalidCastException. This can be remedied by altering the code as follows:
if (obj == null || obj == DependencyProperty.UnsetValue) return base.Equals(obj);
if (!(obj is Currency))
throw new InvalidCastException("The 'obj' argument is not a Currency object.");
return Equals(obj as Currency);
On another note. In the expample when overrding the == operator, a simple comparison is done by calling the Equals method on person1. eg.
public static bool operator ==(Person person1, Person person2)
{
return person1.Equals(person2);
}
This is wrong however, as it is perfectly reasonable to expect that either person1 may be null, especially if you are explicitly testing for null, e.g.
string code = _currency == null ? null : _currency.CurrencyCode;
Therefore, you need to test for null, or check for equality using the static base Equals method.
public static bool operator ==(Person person1, Person person2)
{
return Equals(person1, person2);
}