C# – Equals()

Equals method behaves differently when speaking about reference types and value types.
Generally equals on reference types compares references. If they are the same true is returned.
Equals on value types compares values in fields. If values are the same true is returned.

    [TestClass]
    public class EqualsTests
    {
        /// <summary>
        /// Reference type
        /// </summary>
        class Cat
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        /// <summary>
        /// Value type
        /// </summary>
        struct Dog
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        [TestMethod]
        public void EqualsTestForReferenceTypes()
        {
            var c1 = new Cat() { Name = "John", Age = 1 };
            var c2 = c1;
            var c3 = new Cat() { Name = "John", Age = 1 };

            var c1c2 = c1.Equals(c2); // true (references are equal)
            var c2c3 = c2.Equals(c3); // false
            var c3c1 = c3.Equals(c1); // false
        }

        [TestMethod]
        public void EqualsTestForValueTypes()
        {
            var d1 = new Dog() { Name = "John", Age = 1 };
            var d2 = d1;
            var d3 = new Dog() { Name = "John", Age = 1 };

            var d1d2 = d1.Equals(d2); // true (values in public and private fields are the same)
            var d2d3 = d2.Equals(d3); // true
            var d3d1 = d3.Equals(d1); // true
        }
    }

Of course, in every class Equals method could be overridden. See string example.

        [TestMethod]
        public void EqualsTestForValueTypes2()
        {
            string s1 = "test";
            string s2 = "test";
            var s1s2 = s1.Equals(s2);// true (despite the fact references are not equal)
        }
Advertisements

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