I looked around but no one seems to have asked this question before, so here it goes.
I'm working on a custom class that will have the IEquatable
interface, and as such I'm making my own Equals
method. Here's what it looks like:
public bool Equals(QueryFilter qfilter)
{
if (qfilter == null)
{
return false;
}
return ((this.Value.Equals(qfilter.Value)) &&
(this.Name.Equals(qfilter.Name)) &&
(this.Order == qfilter.Order));
}
Where Value, Name and Order are fields of the QueryFilter class. Value and Name are strings
, but Order is an int
, and I was wondering if using the ==
operator is fine, or if I should go for the Int32.Equals
method, to "match" how the other fields are making their comparisons? I checked the MSDN but it doesn't elaborate much, only saying that it's overloaded, but I'm not sure what that means in this situation. That the ==
will be the one at work always?
So in conclusion, which one is better? Int32.Equals
or ==
? And when should I use each one?
Yes, using the ==
operator is absolutely fine, so long as the compile-time type of Order
is int
.
If the compile-time type were object
for example, then you'd be dealing with boxed int
values and comparing those boxes with reference equality, which isn't what you're after. But so long as the compiler knows they're int
values, it's fine.
Note that it's also fine to do this for Name
and Value
- again, assuming that the compile-time type of those properties is string
(because then the compiler uses the overload provided by string
. Then you can use the fact that &&
is short-circuiting, get rid of unnecessary brackets, and get left with:
public bool Equals(QueryFilter other)
{
return other != null &&
this.Value == other.Value &&
this.Name == other.Name &&
this.Order == other.Order;
}
... which I would certainly prefer to see.
This also handles the case where Value
or Name
is null
, in an obvious way (null references are equal to each other and not equal to any non-null references). Your existing code would throw a NullReferenceException
if it reached this.Value.Equals
or this.Name.Equals
for a null property value. (It may well be that you ensure that's never the case, but it's worth being aware of.)
You should also make sure that your hash code is consistent with equality, and override Equals(object)
too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With