public int CompareTo(object obj) { NumberOfComparisons++; //I know, not thread safe but just for the sample MyComparable mc = obj as MyComparable; if (mc == null) { return(-1); } else { return(NumPart.CompareTo(mc.NumPart)); } }
public void CompareToTest() { MyComparable left = new MyComparable(1); MyComparable right = new MyComparable(2); Assert.IsTrue(left.CompareTo(right) < 0); Assert.IsTrue(left.CompareTo(left) == 0); Assert.IsTrue(right.CompareTo(left) > 0); Assert.IsTrue(left.CompareTo(null) > 0); Assert.IsTrue(((IComparable)left).CompareTo(right) < 0); Assert.IsTrue(((IComparable)left).CompareTo(left) == 0); Assert.IsTrue(((IComparable)right).CompareTo(left) > 0); Assert.IsTrue(((IComparable)left).CompareTo(null) > 0); Assert.Throws <ArgumentException>(delegate { ((IComparable)left).CompareTo(""); }); }
public void EqualsTest() { MyComparable left = new MyComparable(1); MyComparable right = new MyComparable(2); MyComparable left2 = new MyComparable(1); Assert.IsFalse(left.Equals(right)); Assert.IsTrue(left.Equals(left)); Assert.IsFalse(right.Equals(left)); Assert.IsTrue(left.Equals(left2)); Assert.IsFalse(left.Equals(null)); Assert.IsFalse(((object)left).Equals(right)); Assert.IsTrue(((object)left).Equals(left)); Assert.IsFalse(((object)right).Equals(left)); Assert.IsTrue(((object)left).Equals(left2)); Assert.IsFalse(((object)left).Equals(null)); }
public void CallingMethodThroughIComparableInterfaceInvokesImplementingMethod() { MyComparable a = new MyComparable(), b = new MyComparable(); a.result = 534; Assert.AreEqual(534, ((IComparable <MyComparable>)a).CompareTo(b)); Assert.AreStrictEqual(b, a.other); a.result = -42; Assert.AreEqual(-42, ((IComparable <MyComparable>)a).CompareTo(null)); Assert.AreStrictEqual(null, a.other); a.result = -534; Assert.AreEqual(-534, a.CompareTo(b)); Assert.AreStrictEqual(b, a.other); a.result = 42; Assert.AreEqual(42, a.CompareTo(null)); Assert.AreStrictEqual(null, a.other); }
public void CallingMethodThroughIComparableInterfaceInvokesImplementingMethod() { MyComparable a = new MyComparable(), b = new MyComparable(); a.result = 534; Assert.AreEqual(((IComparable <MyComparable>)a).CompareTo(b), 534); Assert.AreStrictEqual(a.other, b); a.result = -42; Assert.AreEqual(((IComparable <MyComparable>)a).CompareTo(null), -42); Assert.AreStrictEqual(a.other, null); a.result = -534; Assert.AreEqual(a.CompareTo(b), -534); Assert.AreStrictEqual(a.other, b); a.result = 42; Assert.AreEqual(a.CompareTo(null), 42); Assert.AreStrictEqual(a.other, null); }