ploeh.github.com
ploeh.github.com copied to clipboard
Maybe<T> has incorrect implementation of Equals, if T is a value type
The implementation of Maybe<T> class in The Maybe functor post https://blog.ploeh.dk/2018/03/26/the-maybe-functor/ has a little issue, when T is a value type. For example:
new Maybe<int>().Equals(new Maybe<int>(0)) // true
Maybe it is better to put a class constraint for T in Maybe<T>
, or implement Equals like this?
public override bool Equals(object obj)
{
var other = obj as Maybe<T>;
if (other == null)
return false;
return !this.HasItem && !other.HasItem
|| this.HasItem && other.HasItem && object.Equals(this.Item, other.Item);
}
Yes, good catch, that's a bug, it should check HasItem
as well.