I've been looking at this piece of code. I realize that the reason why this will always throw the notsupportedexception is because temp is always equal to 20; however, I'd like someone to explain to me why temp is always equal to 20 and not the value that was set to temp in the loop.
{
delegate int Del(int i);
static event Del MyEvent;
static void Main(string[] args)
{
for (int i = 0; i < 20; i++)
MyEvent += a =>
{
int temp = i;
if (a != temp) throw new NotSupportedException();
return a * 2;
};
Console.WriteLine("C'est fini");
Console.WriteLine(GetValue(5));
Console.ReadLine();
}
static int GetValue(int arg)
{
foreach(Del myEvent in MyEvent.GetInvocationList())
{
try
{
return myEvent(arg);
}
catch(NotSupportedException)
{
continue;
}
}
throw new NotSupportedException();
}
}