I am using a System.Collections.Generic
, which contains instances of a class I wrote.
I have read that the collections .Contains
method uses object.Equals()
, or an implementation of the Equals()
method from the IEquatable
interface.
I have overridden the object method, as well as implemented from the interface. However, Queue.Contains(instance)
is always returning false. What am I doing wrong?
For instance...
class Foo : IEquatable<Foo>
{
...
int fooField1;
...
public override bool Equals(object obj)
{
Foo other = obj as Foo;
bool isEqual = false;
if (other.fooField1 == this.fooField1)
{
isEqual = true;
}
return isEqual;
}
public bool Equals(Foo other)
{
bool isEqual = false;
if (other.fooField1 == this.fooField1)
{
isEqual = true;
}
return isEqual;
}
}
...
void SomeFunction()
{
Queue<Foo> Q = new Queue<Foo>();
Foo fooInstance1 = new Foo();
Foo fooInstance2 = new Foo();
fooInstance1.fooField1 = 5;
fooInstance2.fooField1 = 5;
Q.Enqueue(fooInstanec1);
if(Q.Contains(fooInstance2) == false)
{
Q.Enqueue(fooInstance2);
}
}
fooInstance2 is always added to the queue. In fact, when I run this on the debugger, the implementations of Equals are never reached.
What am I doing wrong?