Skip to content

Instantly share code, notes, and snippets.

@jkotas
Created June 7, 2019 05:04
Show Gist options
  • Save jkotas/fa0749d77f0a5073904204a535a14ad2 to your computer and use it in GitHub Desktop.
Save jkotas/fa0749d77f0a5073904204a535a14ad2 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class MyBase : IEquatable<MyBase>
{
public string X { get; set; }
public override bool Equals(object other)
{
MyBase o = other as MyBase;
return (o != null) && Equals(o);
}
public bool Equals(MyBase other) => this.X == other.X;
public override int GetHashCode()
{
var hc = new HashCode();
hc.Add(X);
return hc.ToHashCode();
}
}
// Uncomment to make the repro fail
class MyItem : MyBase // , IEquatable<MyItem>
{
public string Y { get; set; }
public override bool Equals(object other)
{
MyItem o = other as MyItem;
return (o != null) && this.X == o.X && this.Y == o.Y;
}
public bool Equals(MyItem other) => base.Equals((MyBase)other);
public override int GetHashCode()
{
// var hc = new HashCode();
// hc.Add(base.GetHashCode());
// hc.Add(Y);
// return hc.ToHashCode();
// Return poorly distributed hashcode to make the repro fail predictably
return 1;
}
}
class Program
{
static void Main(string[] args)
{
var d = new Dictionary<MyItem, int>()
{
{ new MyItem() { X = "A", Y = "B" }, 1 },
{ new MyItem() { X = "A", Y = "C" }, 2 }
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment