#414 – Equivalence Can Be Based on a Subset of Fields

When you define value equality for a type, you typically compare all fields in the two instances to determine whether they are equivalent.  You can also use just a subset of the fields in the comparison.

Below, two Programmer instances are equivalent if their Name and Age properties match.  But their Mood properties are not used in the comparison.

    public class Programmer
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Mood { get; set; }

        // constructor omitted

        public static bool operator ==(Programmer p1, Programmer p2)
        {
            return (p1.Name == p2.Name) && (p1.Age == p2.Age);
        }

        public static bool operator !=(Programmer p1, Programmer p2)
        {
            return !(p1 == p2);
        }
    }

Test results:

            Programmer p1 = new Programmer("Sean", 47, "Elated");
            Programmer p2 = new Programmer("Sean", 47, "Surly");
            Programmer p3 = new Programmer("Bob", 47, "Surly");

            bool check = (p1 == p2);        // true
            check = (p2 == p3);             // false
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: