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<NameValuePair, string> myNameValueAssetMappings = new Dictionary<NameValuePair, string>();
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<string, string> { internal NameValuePair(string name, string value) : base(name, value) { // left empty }
/// <see cref="object.GetHashCode"/> 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