AyrA icon

C# Operator overloading is great

AyrA | PRO | 12/03/18 10:08:54 PM UTC | 0 ⭐ | 495 👁️ | Never ⏰ | []
C# |

1.83 KB

|

None

|

0 👍

/

0 👎

//https://redd.it/a2r64m
namespace Test
{
    public class Demo
    {
        public int Number { get; private set; }
 
        public Demo(int TestInt)
        {
            Number = TestInt;
        }
 
        public override int GetHashCode()
        {
            //For multiple properties, it's usually a good idea to XOR the Hash code of them all together
            return Number;
        }
 
        public override bool Equals(object obj)
        {
            return obj != null &&
                //Compare hash codes before types because it's faster
                obj.GetHashCode() == GetHashCode() &&
                //Allow comparison with raw integers too
                (obj is int || obj.GetType() == GetType());
        }
 
        public static bool operator ==(Demo A, Demo B)
        {
            return A.Equals(B);
        }
 
        public static bool operator ==(Demo A, int B)
        {
            return A.Equals(B);
        }
 
        public static bool operator !=(Demo A, Demo B)
        {
            return !A.Equals(B);
        }
 
        public static bool operator !=(Demo A, int B)
        {
            return !A.Equals(B);
        }
 
        //Oh boy
        public static bool operator ==(Demo A, object B)
        {
            return true;
        }
 
        public static bool operator !=(Demo A, object B)
        {
            return true;
        }
    }
}
 
//Usage example (all print "True")
 
//Equals
Console.Error.WriteLine((new Demo(1)).Equals(new Demo(1)));
Console.Error.WriteLine((new Demo(1)).Equals(1));
//Operator
Console.Error.WriteLine((new Demo(1)) == (new Demo(1)));
Console.Error.WriteLine((new Demo(1)) == 1);
//Schrödingers Equation
Console.Error.WriteLine((new Demo(1)) == "Cheese");
Console.Error.WriteLine((new Demo(1)) != "Chesse");

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎