(C #) Problems with operator overload ==

I overloaded the == operator from my class as follows:

public static bool operator ==(Table pt1, Table pt2) { return Compare(pt1, pt2) == 0 && pt1.TableName == pt2.TableName; } 

Compare will work the same as strcmp in C ++, returning an integer. The problem is that if I do if (MY_class == null), it will call the my == operator and therefore my Compare function. What are alternatives? put a check on pt1 and pt2 to find out if they are zero? Or just in pt2?

+4
source share
4 answers

You should check the Microsoft manual to implement the '==' operator, as well as to override "Equals ()".

Adapting your example, you need something like:

 public static bool operator ==(Table a, Table b) { // If both are null, or both are same instance, return true. if (System.Object.ReferenceEquals(a, b)) { return true; } // If one is null, but not both, return false. if (((object)a == null) || ((object)b == null)) { return false; } // Return true if the fields match: return Compare(a, b) == 0 && a.TableName == b.TableName; } 
+12
source

You will need zero checks to get the correct behavior. The clearest way to add this check, in my opinion, is to call object.ReferenceEquals(x, null) , as this is a direct call to a non-polymorphic method and is supposedly quite efficient.

+3
source

Just add this line to your statement:

 if ((object)pt1 == null || (object)pt2 == null) return false; 

A cast (object) to prevent recursion (from calling object.== instead of MY_CLASS.== .

Although I'm not sure about the conditions that should arise when comparing null with null.

+2
source

I asked a similar question here . Look at this.

  public bool Equals(ClauseBE other) { if (this._id == other._id) { return true; } return false; } public override bool Equals(Object obj) { if (obj == null) { return base.Equals(obj); } if (!(obj is ClauseBE)) { throw new InvalidCastException("The 'obj' argument is not a ClauseBE object."); } return Equals(obj as ClauseBE); } public override int GetHashCode() { return this._id.GetHashCode(); } public static bool operator ==(ClauseBE a, ClauseBE b) { if (ReferenceEquals(a, null) && ReferenceEquals(b, null)) { return true; } if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Equals(b); } public static bool operator !=(ClauseBE a, ClauseBE b) { return !(a == b); } 
+2
source

Source: https://habr.com/ru/post/1286732/


All Articles