I have a class that imlements IEquatable<T>
. Is it necessary to do a refrence check in Equals()
or is it taken care of in the framework?
class Foo : IEquatable<Foo>
{
int value;
Bar system;
bool Equals(Foo other)
{
return this == other ||
( value == other.value && system.Equals(other.system) );
}
}
In the above example is the this==other
statement superfluous or necessary?
I understand I need to correct the code as follows:
bool Equals(Foo other)
{
if( other==null ) { return false; }
if( object.ReferenceEquals(this, other) ) { return true; } //avoid recursion
return value == other.value && system.Equals(other.system);
}
Thanks for the replies.
I believe that it's necessary. The reference check is the first, quick step you can perform when comparing objects.
In the example you have given, be sure to check that other is not null before accessing its values.
bool Equals(Foo other)
{
if(other == null) return false;
if(this == other) return true;
// Custom comparison logic here.
}