Advertisement
Guest User

class overriding GetHashCode to trick caller

a guest
Dec 24th, 2012
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             HashCodeCheater cheater1 = new HashCodeCheater();
  6.             HashCodeCheater cheater2 = cheater1;
  7.  
  8.             Console.WriteLine("using virtual GetHashCode 1: " + cheater1.GetHashCode());
  9.             Console.WriteLine("using virtual GetHashCode 2: " + cheater2.GetHashCode());
  10.  
  11.             Console.WriteLine("using NON virtual GetHashCode 1: " + RuntimeHelpers.GetHashCode(cheater1));
  12.             Console.WriteLine("using NON virtual GetHashCode 2: " + RuntimeHelpers.GetHashCode(cheater2));
  13.  
  14.             /*            
  15.              * Sample output:
  16.              *
  17.              * using virtual GetHashCode 1: 685172186
  18.              * using virtual GetHashCode 2: 659850042
  19.              * using NON virtual GetHashCode 1: 62476613
  20.              * using NON virtual GetHashCode 2: 62476613
  21.              */
  22.         }
  23.     }
  24.  
  25.     class HashCodeCheater
  26.     {
  27.         private static readonly Random r = new Random();
  28.  
  29.         public override int GetHashCode()
  30.         {
  31.             return r.Next();
  32.         }
  33.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement