Advertisement
AyrA

C# Operator overloading is great

Dec 3rd, 2018
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. //https://redd.it/a2r64m
  2. namespace Test
  3. {
  4.     public class Demo
  5.     {
  6.         public int Number { get; private set; }
  7.  
  8.         public Demo(int TestInt)
  9.         {
  10.             Number = TestInt;
  11.         }
  12.  
  13.         public override int GetHashCode()
  14.         {
  15.             //For multiple properties, it's usually a good idea to XOR the Hash code of them all together
  16.             return Number;
  17.         }
  18.  
  19.         public override bool Equals(object obj)
  20.         {
  21.             return obj != null &&
  22.                 //Compare hash codes before types because it's faster
  23.                 obj.GetHashCode() == GetHashCode() &&
  24.                 //Allow comparison with raw integers too
  25.                 (obj is int || obj.GetType() == GetType());
  26.         }
  27.  
  28.         public static bool operator ==(Demo A, Demo B)
  29.         {
  30.             return A.Equals(B);
  31.         }
  32.  
  33.         public static bool operator ==(Demo A, int B)
  34.         {
  35.             return A.Equals(B);
  36.         }
  37.  
  38.         public static bool operator !=(Demo A, Demo B)
  39.         {
  40.             return !A.Equals(B);
  41.         }
  42.  
  43.         public static bool operator !=(Demo A, int B)
  44.         {
  45.             return !A.Equals(B);
  46.         }
  47.  
  48.         //Oh boy
  49.         public static bool operator ==(Demo A, object B)
  50.         {
  51.             return true;
  52.         }
  53.  
  54.         public static bool operator !=(Demo A, object B)
  55.         {
  56.             return true;
  57.         }
  58.     }
  59. }
  60.  
  61. //Usage example (all print "True")
  62.  
  63. //Equals
  64. Console.Error.WriteLine((new Demo(1)).Equals(new Demo(1)));
  65. Console.Error.WriteLine((new Demo(1)).Equals(1));
  66. //Operator
  67. Console.Error.WriteLine((new Demo(1)) == (new Demo(1)));
  68. Console.Error.WriteLine((new Demo(1)) == 1);
  69. //Schrรถdingers Equation
  70. Console.Error.WriteLine((new Demo(1)) == "Cheese");
  71. Console.Error.WriteLine((new Demo(1)) != "Chesse");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement