Efficient Object Equality C#
<p>I am trying to improve performance on the following (sample) code.</p>

<pre><code>Object[] inputKeys = new Object[10];
inputKeys[0] = "4021";
inputKeys[1] = "3011";
inputKeys[2] = "1010";
inputKeys[3] = "1020";
inputKeys[4] = "1030";
</code></pre>

<p>then the input keys are compared.</p>

<pre><code>for (int i = 0; i &lt; 5; i++)
{
    for (int j = 0; j &lt; 5; j++)
    {
        bool result = inputKeys[i].Equals(inputKeys[j]);
    }
}
</code></pre>

<p>The inputKeys can be all of type <code>string</code>, <code>int32</code> or <code>DateTime</code>.</p>

<p>There is a huge performance drop in <strong><code>.Equals</code></strong> line, when it hits millions of times.</p>

<p><strong>Any suggestions on how to improve performance of this line (the equality check)?</strong></p>

<p>I have tried this:
Using an array of below class instead of the Object array to hold the keys. There I keep the Key type and key values.</p>

<pre><code>public class CustomKey : IEquatable&lt;CustomKey&gt;{
    internal int KeyType { get; private set; }

    internal string ValueString { get; private set; }
    internal int ValueInteger { get; private set; }
    internal DateTime ValueDateTime { get; private set; }

    internal CustomKey(string keyValue)
    {
        this.KeyType = 0;
        this.ValueString = (string)keyValue;
    }

    internal CustomKey(int keyValue)
    {
        this.KeyType = 1;
        this.ValueInteger = (int)keyValue;
    }

    internal CustomKey(DateTime keyValue)
    {
        this.KeyType = 2;
        this.ValueDateTime = (DateTime)keyValue;
    }

    public bool Equals(CustomKey other)
    {
        if (this.KeyType != other.KeyType)
        {
            return false;
        }
        else
        {
            if (this.KeyType == 0)
            {
                return this.ValueString.Equals(other.ValueString);
            }
            else if (this.KeyType == 1)
            {
                return this.ValueInteger.Equals(other.ValueInteger);
            }
            else if (this.KeyType == 2)
            {
                return this.ValueDateTime.Equals(other.ValueDateTime);
            }
            else
            {
                return false;
            }
        }
    }
}
</code></pre>

<p>But the performance was worse.</p>
