C# Queue problem

c#, queue, reference

Solution

The simplest way is to override `Equals` so that one `XYNode` knows whether it's equal to another `XYNode`. You should override `GetHashCode()` at the same time, and possibly also implement `IEquatable<XYNode>` to allow a strongly-typed equality comparison.

Alternatively, you could write an `IEqualityComparer<XYNode>` implementation to compare any two nodes and return whether or not they're the same - and then pass that into the call to the appropriate overload of the `Contains` extension method defined in `Enumerable` (assuming you're using .NET 3.5).

Further things to consider:

- Could you use private fields instead of protected ones?

- Could your class be sealed?

- Could your class be immutable?

- Should your class perhaps be a struct instead? (Judgement call...)

- Should you overload the == and != operators?

Problem

Suppose I have a class ``` XYNode { protected int mX; protected int mY; } ``` and a queue ``` Queue<XyNode> testQueue = new Queue<XYNode>(); ``` I want to check if a node with that specific x and y coordinate is already in the queue. The following obviously doesn't work : ``` testQueue.Contains(new XYNode(testX, testY)) ``` because even if a node with those coordinates is in the queue, we're testing against a different XYNode object so it will always return false. What's the right solution ?

Original source