Code understanding issues
<p>I was reading a source code this morning when I came across a C# code sample that I don't understand:</p>

<pre><code>public bool Dequeue(out T value)
{
    Node head;
    Node tail;
    Node next;

    while (true)
    {
        // read head
        head = this.head;
        tail = this.tail;
        next = head.Next;

        // Are head, tail, and next consistent?
        if (Object.ReferenceEquals(this.head, head))
        {
           // Source code continues here...
        }
        // And here...
    }
}
</code></pre>

<p>The line I've got an issue with it the one which contains <code>Object.ReferenceEquals()</code>.</p>

<p>If I understand well, the source code author wants to compare <code>this.head</code> and <code>head</code> but on the lines above, he just wrote <code>head = this.head</code>.</p>

<p>Coming mainly from a <code>C++</code> background, this statement makes no sense to me. Moreover, under some circunstances, it seems that the <code>Object.ReferenceEquals()</code> line throws a <code>System.NullReferenceException</code> so it certainly does something, I just can't figure out what.</p>

<p>Can you help me understanding what this line does and possibly why ?</p>

<p>In case you need this, here is the <code>Node</code> class definition (I guess it is a "template" class, not sure of the wording for C#):</p>

<pre><code>private class Node
{
    public T Value;
    public Node Next;

    public Node(T value)
    {
        this.Value = value;
    }
}
</code></pre>

<p>Thank you.</p>

<h2>Edit: The rest of the method, for those who asked</h2>

<pre><code>    public void Enqueue(T value)
    {
        // Allocate a new node from the free list
        Node valueNode = new Node(value);

        while (true)
        {
            Node tail = this.tail;
            Node next = tail.Next;

            // are tail and next consistent
            if (Object.ReferenceEquals(tail, this.tail))
            {
                // was tail pointing to the last node?
                if (Object.ReferenceEquals(next, null))
                {
                    if (Object.ReferenceEquals(
                            Interlocked.CompareExchange(ref tail.Next, valueNode, next),
                            next
                            )
                        )
                    {
                        Interlocked.CompareExchange(ref this.tail, valueNode, tail);
                        break;
                    }
                }
                else // tail was not pointing to last node
                {
                    // try to swing Tail to the next node
                    Interlocked.CompareExchange&lt;Node&gt;(ref this.tail, next, tail);
                }
            }
        }
    }
</code></pre>
