Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int32.Equals vs '==' operator

Tags:

operators

c#

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?

like image 572
Ana Ameer Avatar asked Dec 02 '22 20:12

Ana Ameer


1 Answers

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.

like image 141
Jon Skeet Avatar answered Dec 16 '22 02:12

Jon Skeet