A
Ashish Khandelwal
-----See below code,
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
int hash = str.GetHashCode() ; // Returns 175803953
int hash1 = str1.GetHashCode(); // Returns 175803953
Hashtable ht = new Hashtable();
ht.Add(hash ,strValue);
ht.Add(hash1,strValue1); // ****ERROR****
string strTmp = (string) ht[str];
string strTmp1 = (string) ht[hash1];
In Above code when i try to call GetHashCode() for both str and str1,
it returns me same Hash Code '175803953', and that's why when i try to
add into hashtable, exception generates which is normal (i know we
cannot add same key twice). Now.... see below code
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
Hashtable ht = new Hashtable();
ht.Add(str,strValue);
ht.Add(str1,strValue1);
the above code runs perfectly without any error, so now here i want to
understand one thing, as HashTable calls GetHashCode() method to get
the Hash Code of passed key and as we show in the 1st example that the
both strings are generating the same Hash Code so why there is no
exception in the 2nd example,
Does HashTable use some other algorithm to generate the Hash Code of
passed key? if so, i think then its always better to assign object
directly as a key in stand of first generate the Hash Code and then
assign it to HashTable as a key.
(My main concentration on String as a Key)
Please help me to understand...
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
int hash = str.GetHashCode() ; // Returns 175803953
int hash1 = str1.GetHashCode(); // Returns 175803953
Hashtable ht = new Hashtable();
ht.Add(hash ,strValue);
ht.Add(hash1,strValue1); // ****ERROR****
string strTmp = (string) ht[str];
string strTmp1 = (string) ht[hash1];
In Above code when i try to call GetHashCode() for both str and str1,
it returns me same Hash Code '175803953', and that's why when i try to
add into hashtable, exception generates which is normal (i know we
cannot add same key twice). Now.... see below code
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
Hashtable ht = new Hashtable();
ht.Add(str,strValue);
ht.Add(str1,strValue1);
the above code runs perfectly without any error, so now here i want to
understand one thing, as HashTable calls GetHashCode() method to get
the Hash Code of passed key and as we show in the 1st example that the
both strings are generating the same Hash Code so why there is no
exception in the 2nd example,
Does HashTable use some other algorithm to generate the Hash Code of
passed key? if so, i think then its always better to assign object
directly as a key in stand of first generate the Hash Code and then
assign it to HashTable as a key.
(My main concentration on String as a Key)
Please help me to understand...