Skip to main content
title format
Source Link

Faulty implementation of overriden == operator in C#:

C#

Faulty implementation of overriden `==` operator:
public class MyClass { public int A { get; set; } public static bool operator ==(MyClass obj1, MyClass obj2) { if (obj1 == null) { return obj2 == null; } else { return obj1.Equals(obj2); } } public static bool operator !=(MyClass obj1, MyClass obj2) { return !(obj1 == obj2); } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) { return false; } else { return A == other.A; } } } 

One might say it's obvious that operator== calls itself by using the == operator, but you usually do not think that way about ==, so it's easy to fall into that trap.

Faulty implementation of overriden == operator in C#:

public class MyClass { public int A { get; set; } public static bool operator ==(MyClass obj1, MyClass obj2) { if (obj1 == null) { return obj2 == null; } else { return obj1.Equals(obj2); } } public static bool operator !=(MyClass obj1, MyClass obj2) { return !(obj1 == obj2); } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) { return false; } else { return A == other.A; } } } 

One might say it's obvious that operator== calls itself by using the == operator, but you usually do not think that way about ==, so it's easy to fall into that trap.

C#

Faulty implementation of overriden `==` operator:
public class MyClass { public int A { get; set; } public static bool operator ==(MyClass obj1, MyClass obj2) { if (obj1 == null) { return obj2 == null; } else { return obj1.Equals(obj2); } } public static bool operator !=(MyClass obj1, MyClass obj2) { return !(obj1 == obj2); } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) { return false; } else { return A == other.A; } } } 

One might say it's obvious that operator== calls itself by using the == operator, but you usually do not think that way about ==, so it's easy to fall into that trap.

Source Link

Faulty implementation of overriden == operator in C#:

public class MyClass { public int A { get; set; } public static bool operator ==(MyClass obj1, MyClass obj2) { if (obj1 == null) { return obj2 == null; } else { return obj1.Equals(obj2); } } public static bool operator !=(MyClass obj1, MyClass obj2) { return !(obj1 == obj2); } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) { return false; } else { return A == other.A; } } } 

One might say it's obvious that operator== calls itself by using the == operator, but you usually do not think that way about ==, so it's easy to fall into that trap.