-
-
Save bgeihsgt/e1cb0312184c22df22ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace ValueTypeEquality | |
{ | |
[TestClass] | |
public class Sample | |
{ | |
[TestMethod] | |
public void SampleTest() | |
{ | |
TheType<MyValueType>.ShouldHaveValueEqualitySemantics(() => new MyValueType(4), () => new MyValueType(5)); | |
} | |
} | |
public class TheType<T> | |
{ | |
private class NotT | |
{ | |
} | |
public static void ShouldHaveValueEqualitySemantics(Func<T> makeA, Func<T> makeB) | |
{ | |
var a = makeA(); | |
var aPrime = makeA(); | |
var b = makeB(); | |
Assert.IsTrue(a.Equals(aPrime)); | |
Assert.IsTrue(a.GetHashCode().Equals(aPrime.GetHashCode())); | |
Assert.IsFalse(a.Equals(b)); | |
Assert.IsFalse(a.GetHashCode().Equals(b.GetHashCode())); | |
Assert.IsFalse(a.Equals(null)); | |
Assert.IsFalse(a.Equals(new NotT())); | |
Assert.AreEqual(a, aPrime); | |
Assert.AreNotEqual(a, b); | |
} | |
} | |
public class MyValueType : IEquatable<MyValueType> | |
{ | |
private readonly int _value; | |
public MyValueType(int value) | |
{ | |
_value = value; | |
} | |
public bool Equals(MyValueType other) | |
{ | |
return _value == other._value; | |
} | |
public override bool Equals(object obj) | |
{ | |
var other = obj as MyValueType; | |
if (other == null) | |
{ | |
return false; | |
} | |
return Equals(other); | |
} | |
public override int GetHashCode() | |
{ | |
return _value.GetHashCode(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment