Override Equals Method Of Value Types

Override Equals method of value types

Hello everybody.

Today I want to give some demo.

using System;
using System.Diagnostics;

namespace StackOverflowQuest
{
    class Program
    {
        struct StructTest
        {
            public string TestString { get; set; }

            //public override bool Equals(object obj)
            //{
            //    var ct = (StructTest)obj;
            //    return ct.TestString == this.TestString;
            //}
        }
        class ClassTest
        {
            public string TestString { get; set; }

            public override bool Equals(object obj)
            {
                var ct = obj as ClassTest;
                if (ct == null)
                    return false;
                return ct.TestString == this.TestString;
            }
        }

        static void Main(string[] args)
        {
            StructTest st = new StructTest() { TestString = "water"};
            StructTest st2 = new StructTest() { TestString = "water" };

            ClassTest ct1 = new ClassTest() { TestString = "water" };
            ClassTest ct2 = new ClassTest() { TestString = "water" };

            int numberOfIterations = 500000;

            Stopwatch sw2 = new Stopwatch();
            sw2.Start();
            for (int i = 0; i < numberOfIterations; i++)
            {
                ct1.Equals(ct2);
            }
            sw2.Stop();
            Console.WriteLine("class perfomance = {0} Elapsed Milliseconds", sw2.ElapsedMilliseconds);

            Stopwatch sw1 = new Stopwatch();
            sw1.Start();
            for(int i = 0; i < numberOfIterations; i++)
            {
                st.Equals(st2);
            }
            sw1.Stop();
            Console.WriteLine("structs perfomance = {0}  Elapsed Milliseconds", sw1.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }
}

Take note of commented method of Equals method. If I execute that code on my machine, I'm getting difference in perfomance in 6 times. But if to uncomment Equals, then class and struct have comparable perfomance.

No Comments

Add a Comment
Comments are closed