Writing and calling operator ==

Nov 12 2004 8:51 PM
In C++, I totally understand the use of operator==(). But in C#, there are some nuances that I just don't quite grasp yet. I've created a class called Person, and I'm trying to test one object of type Person with another. So I call it like this: if (person1 == person2) { ... } Now, even though all of the attributes of person1 are the same as the attributes of person2, this test for equality is false -- the persons are not equal. So, I think to myself, "This means I should write an operator==() function for my Person class." And in this operator==() method, I check that all the attributes are the same, and I return true if they are, and life is good ... ... until I try to call this code: if (person3 == null) { ... } At this point I get a "System.NullReferenceException" exception, because -- well, person3 IS null, and so the operator==() method is trying to test members that don't exist. Clearly, what's happening here is that I don't understand how to test "person1" and "person2" for OBJECT or CLASS equality, while also testing "person3" for POINTER equality. What is wrong with my thought process and what is wrong with my understanding, and how SHOULD I be dealing with this problem? What should I be doing differently than I'm doing here, and what do I need to know about operator overloading in C# that's different from what I was doing in C++? Thanks, Brian / Cove

Answers (8)