0

Why does this example gives me ten times 10?

namespace ConsoleApp
{
    internal class Program
    {
        delegate void Printer();
        static void Main(string[] args)
        {
            List<Printer> printers = new List<Printer>();

            
            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { Console.WriteLine(i); });
            }
            foreach (var printer in printers)
            {
                printer();
            }
        }
    }
}

I expected it to throw an exception because i don't exist outside the loop. I read a question on this forum with a similar topic and they mentioned how the scope and lifetime of the variable differ, but I'm still not sure what does that exactly mean. Does i hold some kind of reference count and wait for it to become 0?

Aaras
  • 9
  • 3
  • It's called a *captured variable*. Notice what happens if you do `for (int i = 0; i < 10; i++) { var j = i; printers.Add(() => Console.WriteLine(j)); }` – Charlieface Jun 13 '23 at 23:42
  • IL doesn't support "captured variables" or "lambda methods". These C# features are implemented in the C# compiler by defining extra types. Reading the output of a C# decompiler will show you how it actually works, and may help you understand why. eg https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQAwAIpwCwG5nJQDMmMmcA7MujegN7W1PACmANiwOYCGALi5mzoACgCcAlgDt+ogBQBKfEiZMsANkHoAstymysqANoBddN1GcAzvMYr6tu7QAy4y7wA8YqTIB86AA4S0iyilugAvOiSLADu6C5unkG+CkoOjujpjgBmAPai6LLe6OIR6Ki4Jeju6HAVJWBgNsoZtAwtrSqB3iGWAHQAgsDAsqwcPPz05ACcRYroAL6KWXYLKyp5oizcAMYAFoUAbuYBySElkqc9oc2dNO13XWdyyx2ta29MH19AA=== – Jeremy Lakeman Jun 14 '23 at 03:17

0 Answers0