title: What Interlocked.CompareExchange is used for in the dapper .net method?
body: <p>In dapper code in <code>Link.TryAdd</code> method, there is the following piece of code:</p>
  
  <pre><code>var snapshot = Interlocked.CompareExchange(ref head, null, null);
  </code></pre>
  
  <p>Why is this required instead of simple:</p>
  
  <pre><code>var snapshot = head;
  </code></pre>
  
  <p>both lines do not change the value of <code>head</code>, both lines assign the value of <code>head</code> to <code>snapshot</code>. Why the first one was chosen over the second?</p>
  
  <p><strong>Edit:</strong> the code I'm referring to is here: <a href="https://github.com/SamSaffron/dapper-dot-net/blob/77227781c562e65c167bf7a933d69291d5bdc6f3/Dapper/SqlMapper.cs" rel="nofollow">https://github.com/SamSaffron/dapper-dot-net/blob/77227781c562e65c167bf7a933d69291d5bdc6f3/Dapper/SqlMapper.cs</a></p>