title: Why does a lambda expression in C# cause a memory leak?
body: <p>Note: this is not just some random useless code, this is an attempt to reproduce an issue with lambda expressions and memory leaks in C#.</p>
  
  <p>Examine the following program in C#. It's a console application that simply:</p>
  
  <ol>
  <li>Creates a new object of type Test</li>
  <li>Writes to the console that the object was created</li>
  <li>Calls garbage collection</li>
  <li>Wait for any user input</li>
  <li>Shuts down</li>
  </ol>
  
  <p>I run this program using JetBrains DotMemory, and I take two memory snapshots: one after the object was initialized, and another after its been collected. I compare the snapshots and get what I expect: one dead object of type Test.</p>
  
  <p>But here's the quandary: I then create a local lambda expression inside the object's constructor and I DO NOT USE IT ANYWHERE. It's just a local constructor variable. I run the same procedure in DotMemory, and suddenly, I get an object of type Test+&lt;>, which survives garbage collection.</p>
  
  <p>See the attached retention path report from DotMemory: The lambda expression has a pointer to the Test+&lt;> object, which is expected. But who has a pointer to the lambda expression, and why is it kept in memory?</p>
  
  <p>Also, this Test+&lt;> object - I assume it is just temporary object to hold the lambda method, and has nothing to do with the original Test object, am I right?</p>
  
  <pre><code>public class Test
  {
      public Test()
      {
          // this line causes a leak
          Func&lt;object, bool&gt; t = _ =&gt; true;
      }
  
      public void WriteFirstLine()
      {
          Console.WriteLine("Object allocated...");
      }
  
      public void WriteSecondLine()
      {
          Console.WriteLine("Object deallocated. Press any button to exit.");
      }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          var t = new Test();
          t.WriteFirstLine();
          Console.ReadLine();
          t.WriteSecondLine();
          GC.Collect();
          GC.WaitForPendingFinalizers();
          GC.Collect();
  
          Console.ReadLine();
      }
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/oKZvf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oKZvf.png" alt="DotMemory retention path report"></a></p>