Skip to content

Instantly share code, notes, and snippets.

@bgeihsgt
Forked from JayBazuzi/ValueTypeAssertions.cs
Created June 7, 2014 00:07
Show Gist options
  • Save bgeihsgt/e1cb0312184c22df22ed to your computer and use it in GitHub Desktop.
Save bgeihsgt/e1cb0312184c22df22ed to your computer and use it in GitHub Desktop.
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