If you want to unique hashcode then there are 2 ways
1] requirement is equality mean if value contain in object should return same hashcode in this scenario you can use "Object.GetHashCode()" method.
2] requirement is identity mean if object contain same value but different instance should
return different hashcode, you can use "RuntimeHelpers.GetHashCode" method
Here you can find same hashcode for string becuase of CLR's intern pool for string.
Example
using System.Runtime.CompilerServices; <<<======= RuntimeHelpers class
namespace GetHashCodeSample
{
class Program
{
static void Main(string[] args)
{
string s1 = "nitin";
string s2 = "nitin";
int i = 1;
int j = 1;
System.Console.WriteLine("Using Object's GetHashCode");
System.Console.WriteLine("s1:{0}, s2 {1}", s1.GetHashCode(), s2.GetHashCode());
System.Console.WriteLine("Using RuntimeHelper's GetHashCode");
System.Console.WriteLine("s1:{0}, s2 {1}", RuntimeHelpers.GetHashCode(s1), RuntimeHelpers.GetHashCode(s2));
System.Console.WriteLine("Using RuntimeHelper's GetHashCode");
System.Console.WriteLine("i:{0}, j {1}", RuntimeHelpers.GetHashCode(i), RuntimeHelpers.GetHashCode(j));
System.Console.ReadLine();
}
}
}
Using Object's GetHashCode
s1:-1904952336, s2 -1904952336
Using RuntimeHelper's GetHashCode
s1:37121646, s2 37121646
Using RuntimeHelper's GetHashCode
i:45592480, j 57352375
No comments:
Post a Comment