title: Does Linq's IEnumerable.Select return a reference to the original IEnumerable?
body: <p>I was trying to clone an List in my code, because I needed to output that List to some other code, but the original reference was going to be cleared later on. So I had the idea of using the <code>Select</code> extension method to create a new reference to an <code>IEnumerable</code> of the same elements, for example:</p>
  
  <pre><code>List&lt;int&gt; ogList = new List&lt;int&gt; {1, 2, 3};
  IEnumerable&lt;int&gt; enumerable = ogList.Select(s =&gt; s);
  </code></pre>
  
  <p>Now after doing <code>ogList.Clear()</code>, I was surprised to see that my new enumerable was also empty.</p>
  
  <p>So I started fiddling around in LINQPad, and saw that even if my <code>Select</code> returned different objects entirely, the behaviour was the same.</p>
  
  <pre><code>List&lt;int&gt; ogList = new List&lt;int&gt; {1, 2, 3};
  IEnumerable&lt;int&gt; enumerable = ogList.Select(s =&gt; 5); // Doesn't return the original int
  enumerable.Count().Dump(); // Count is 3
  ogList.Clear();
  enumerable.Count().Dump(); // Count is 0!
  </code></pre>
  
  <p>Note that in LINQPad, the <code>Dump()</code>s are equivalent to <code>Console.WriteLine()</code>.</p>
  
  <p>Now probably my need to clone the list in the first place was due to bad design, and even if I didn't want to rethink the design I could easily clone it properly. But this got me thinking about what the <code>Select</code> extension method actually <strong>does</strong>.</p>
  
  <p>According to the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.7.2" rel="nofollow noreferrer">documentation</a> for <code>Select</code>:</p>
  
  <blockquote>
    <p>This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.</p>
  </blockquote>
  
  <p>So then I tried adding this code before clearing:</p>
  
  <pre><code>foreach (int i in enumerable)
  {
      i.Dump();
  }
  </code></pre>
  
  <p>The result was still the same.</p>
  
  <p>Finally, I tried one last thing to figure out if the reference in my new enumerable was the same as the old one. Instead of clearing the original List, I did:</p>
  
  <pre><code>ogList.Add(4);
  </code></pre>
  
  <p>Then I printed out the contents of my enumerable (the "cloned" one), expecting to see '4' appended to the end of it. Instead, I got:</p>
  
  <pre><code>5
  5
  5
  5 // Huh?
  </code></pre>
  
  <p>Now I have no choice but to admit that I have no idea how the Select extension method works behind the scenes. What's going on?</p>