none
Why do we need to define both == & != RRS feed

  • Question

  • I am just curious about this. I don't have any particular difficulty dealing with it.

    When defining "==" for an object, you also need to define "!=". Why is this? Isn't "!=" always completely implied by "=="? (and for that matter by "Equals")? I have never defined != in any way other than

          public static bool operator !=(object obj1, object obj2)
            {
                return !(obj1 == obj2);
            }

    And if there is some circumstance that you might want them to be different, wouldn't it make sense to have defining != be optional?

    Thanks,

    Ethan


    Ethan Strauss

    Tuesday, March 3, 2020 4:05 PM

Answers

  • And if there is some circumstance that you might want them to be different

    Imagine that you are comparing objects that you have read from a database and they allow NULLs. Then, if you want the behavior to be the same as they have in the database, NULL==NULL is always false (two NULLS are not equal to each other) and NULL!=NULL is also false. So you can't take for granted that == is the negation of !=.
    • Marked as answer by Ethan Strauss Tuesday, March 3, 2020 8:58 PM
    Tuesday, March 3, 2020 8:47 PM
    Moderator

All replies

  • And if there is some circumstance that you might want them to be different

    Imagine that you are comparing objects that you have read from a database and they allow NULLs. Then, if you want the behavior to be the same as they have in the database, NULL==NULL is always false (two NULLS are not equal to each other) and NULL!=NULL is also false. So you can't take for granted that == is the negation of !=.
    • Marked as answer by Ethan Strauss Tuesday, March 3, 2020 8:58 PM
    Tuesday, March 3, 2020 8:47 PM
    Moderator
  • Weird, but I guess that makes sense. If you have two unset values you don't want to assume that they are either the same or that they are different. They are kind of like Schrodinger's cat.

    Thanks!

    Ethan


    Ethan Strauss

    Tuesday, March 3, 2020 8:57 PM