Forums - C# Corner

Forum guidelines
Sumitra Paul

Sumitra Paul

  • 1.3k
  • 51
  • 21.1k

Uses of GetHashCode and Equals

Nov 25 2012 1:57 AM

Hi,

I am trying to understand a piece of code which basically uses GetHashCode() and Equals(). I googled it but still can't find any good artical to understand. MsDN has something but cud'nt understand.

The below metioned code has been used in my app class library. I have taken it out and put it in console app and used some constant value just to make it compilable.

Can someone explain me the use of NameValuePair class from below code snippet. More specifically the use of GetHashCode and Equals (If posible if you can put line by line comment for each line for method GetHashCode and Equals stating why we have written it, wud be great).


Code:


 class Program
    {
        private static readonly IDictionary myNameValueAssetMappings =
            new Dictionary();

        static void Main(string[] args)
        {
            // some code

            var pair = ConstructNameValuePair("someName", "SomeValue");
            if (pair != null)
            {
                myNameValueAssetMappings[pair] = "20000"; // this value will be coming from somewhere else
            }

            Console.ReadKey();
        }

        private static NameValuePair ConstructNameValuePair(string name, string value)
        {
           // some code

            return new NameValuePair(name, value);
        }  

        #region NameValuePair

        private sealed class NameValuePair : Tuple
        {

            internal NameValuePair(string name, string value) :
                base(name, value)
            {
                // left empty
            }

            ///
            public override int GetHashCode()
            {
                return Item1.GetHashCode() + 5 * Item2.GetHashCode();
            }

            public override bool Equals(object obj)
            {
                if (obj == this)
                {
                    return true;
                }
                var otherPair = obj as NameValuePair;
                if (otherPair == null)
                {
                    return false;
                }
                return otherPair.Item1 == Item1 &&
                       otherPair.Item2 == Item2;
            }
        }

        #endregion
    }

Thanks a lot for taking time to read this.

your help will be highly appriciated.

Best Regards.

v


Answers (1)

Visual Studio Live - Redmond 2016

SPONSORED BY

C# Corner Chandigarh DevCon16
Chandigarh DevCon16 is a one-day Developer Conference where programmers, technologists, authors, and members meet, demonstrate, plan, and hang out.