1

I've read some stuff about overriding Equal and GetHashcode but do I need it when just having a simple own Equal method like below?

And if I do have to override it:

Why is that? - Should I use Id.GetHashCode() when overriding GetHashCode()?

public class Foo {
    public Guid Id { get; } = new Guid();

    public bool Equal(Foo other) {
        if (other == null) return false;
        return Id == other.Id;
    }
}
MrProgram
  • 5,044
  • 13
  • 58
  • 98
  • @Muds but my code above doesnt override Equals? It's just a new method? – MrProgram Jan 13 '16 at 12:11
  • If there are no additional conventions then you don't really need to but I don't see a reason to reinvent the wheel especially since it won't work in conjunction with all the default implementation of comparing two instances. – dryman Jan 13 '16 at 12:17

2 Answers2

4

Your code looks like you want to implement IEquatable<Foo> for your object. And MSDN advice to oveeride Object.Equals() method:

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
  • Thank you. Just one question..What do I return when overriding GetHashCode()? Id.GetHashCode()? – MrProgram Jan 13 '16 at 12:14
  • 1
    Overriding GetHashCode is another not simple question. For a type with one property you can return just Id.GetHashCode. See also this question and answer about it: http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode – Vadim Martynov Jan 13 '16 at 12:17
1

Another pointer to your solution can be found here - It explains what all are your options -- please have a read

Typically, you implement value equality when objects of the type are expected to be added to a collection of some sort, or when their primary purpose is to store a set of fields or properties. You can base your definition of value equality on a comparison of all the fields and properties in the type, or you can base the definition on a subset.

Community
  • 1
  • 1
Muds
  • 4,006
  • 5
  • 31
  • 53