ploeh.github.com icon indicating copy to clipboard operation
ploeh.github.com copied to clipboard

Maybe<T> has incorrect implementation of Equals, if T is a value type

Open spirit11 opened this issue 4 years ago • 1 comments

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);
	}

spirit11 avatar Jun 07 '20 11:06 spirit11

Yes, good catch, that's a bug, it should check HasItem as well.

ploeh avatar Jun 07 '20 12:06 ploeh