CSHARP_1001_NOTES Telegram 729
😈 Хитрая задачка на C# — замыкания и ловушка в цикле

Что выведет этот код?


var actions = new List<Action>();

for (int i = 0; i < 5; i++)
{
actions.Add(() => Console.WriteLine(i));
}

foreach (var action in actions)
{
action();
}


На первый взгляд кажется, что будет:


0
1
2
3
4

Но на самом деле вывод:


5
5
5
5
5


💡 Почему?
Все лямбды замкнулись на одну и ту же переменную i, и когда они выполняются — i уже стало 5.

Как исправить:


for (int i = 0; i < 5; i++)
{
int copy = i;
actions.Add(() => Console.WriteLine(copy));
}


Теперь всё работает как ожидается.

🧠 Замыкания в C# захватывают переменные, а не их значения! Аккуратнее с циклами и лямбдами.



tgoop.com/csharp_1001_notes/729
Create:
Last Update:

😈 Хитрая задачка на C# — замыкания и ловушка в цикле

Что выведет этот код?


var actions = new List<Action>();

for (int i = 0; i < 5; i++)
{
actions.Add(() => Console.WriteLine(i));
}

foreach (var action in actions)
{
action();
}


На первый взгляд кажется, что будет:


0
1
2
3
4

Но на самом деле вывод:


5
5
5
5
5


💡 Почему?
Все лямбды замкнулись на одну и ту же переменную i, и когда они выполняются — i уже стало 5.

Как исправить:


for (int i = 0; i < 5; i++)
{
int copy = i;
actions.Add(() => Console.WriteLine(copy));
}


Теперь всё работает как ожидается.

🧠 Замыкания в C# захватывают переменные, а не их значения! Аккуратнее с циклами и лямбдами.

BY C# 1001 notes


Share with your friend now:
tgoop.com/csharp_1001_notes/729

View MORE
Open in Telegram


Telegram News

Date: |

Hui said the time period and nature of some offences “overlapped” and thus their prison terms could be served concurrently. The judge ordered Ng to be jailed for a total of six years and six months. Click “Save” ; For crypto enthusiasts, there was the “gm” app, a self-described “meme app” which only allowed users to greet each other with “gm,” or “good morning,” a common acronym thrown around on Crypto Twitter and Discord. But the gm app was shut down back in September after a hacker reportedly gained access to user data. fire bomb molotov November 18 Dylan Hollingsworth yau ma tei Just at this time, Bitcoin and the broader crypto market have dropped to new 2022 lows. The Bitcoin price has tanked 10 percent dropping to $20,000. On the other hand, the altcoin space is witnessing even more brutal correction. Bitcoin has dropped nearly 60 percent year-to-date and more than 70 percent since its all-time high in November 2021.
from us


Telegram C# 1001 notes
FROM American