Overload == and != to make comparing two structs easy in C#

Sorry I only had three posts last week. I try for around five per week but sometimes things get hectic and I got stuck on a really complicated example. That also made me realize that I've been posting some pretty tough material lately. I'll try to make some easier posts this week, but then I've got some more really interesting things ready for next week!
For reference types (classes), == returns true if two references refer to the same object (reference equality). It returns false if two references refer to different objects that happen to have the same values (value equality).

(The article Guidelines for Overloading Equals() and Operator == (C# Programming Guide) says you can override Equals if you like to test value equality but they recommend that you leave == alone so it tests reference equality for reference types.)

Structs, however, are value types not reference types. A struct's Equals method is defined by default to return value equality and == isn't defined at all so you can't use == to compare two structs.

This example uses the following code to override == for the Person class to check value equality. The Human class is similar but doesn't override ==.

private struct Person
{
    public string FirstName, LastName;

    public static bool operator ==(Person per1, Person per2)
    {
        return per1.Equals(per2);
    }
    public static bool operator !=(Person per1, Person per2)
    {
        return per1.Equals(per2);
    }

    //public override bool Equals(object obj)
    //{
    //    return base.Equals(obj);
    //}
    //public override int GetHashCode()
    //{
    //    return base.GetHashCode();
    //}
};

private struct Human
{
    public string FirstName, LastName;
};

Both of these classes define FirstName and LastName fields.

The Person class overrides == so it uses the default implementation of Equals to test value equality. It also overrides != to return the negation of ==. Note that == and != come in pairs so if you override one you must also override the other.

Also note that if you override == and != then Visual Studio warns you if you do not also override Equals and GetHashCode. You can uncomment out the code shown above to make Visual Studio shut up about that.

The following code shows how the program tests == for the Person struct.

private void Form1_Load(object sender, EventArgs e)
{
    Person person1 = new Person() { FirstName = "Rod", LastName = "Stephens" };
    Person person2 = new Person() { FirstName = "Rod", LastName = "Stephens" };
    Person person3 = new Person() { FirstName = "Ann", LastName = "Archer" };
    Human human1 = new Human() { FirstName = "Rod", LastName = "Stephens" };
    Human human2 = new Human() { FirstName = "Rod", LastName = "Stephens" };

    // Use == for Persons.
    string result = "person1 == person2: " + (person1 == person2).ToString() + "\r\n";
    result += "person1 == person3: " + (person1 == person3).ToString() + "\r\n";

    // Use == for Humans. This isn't allowed.
    //bool humans_equal = (human1 == human2);
    //result += "human1 == human2: " + humans_equal.ToString() + "\r\n";

    txtResults.Text = result;
    txtResults.Select(0, 0);
}

The code makes some Person and Human variables. It then uses == to see whether some of them are equal. The code that compares Human structs is commented out because == is not defined for Human so Visual Studio won't let that code compile.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.