lambda iteration variables

In this chapter you will learn:

  1. lambda and iteration variables

lambda and iteration variables

using System;/*from   ja v a2s  .c  o  m*/

class Program
{
    public static void Main()
    {
        Action[] actions = new Action[3];

        for (int i = 0; i < 3; i++) { 
            actions[i] = () => Console.WriteLine(i);
        }
        for (int i = 0; i < 3; i++)
        {
            actions[i]();
        }
        
    }
}

The output:

The fix the problem:

using System;//from ja v a 2  s  .  c  o m

class Program
{
    public static void Main()
    {
        Action[] actions = new Action[3];

        int i = 0;
        actions[0] = () => Console.Write(i);
        i = 1;
        actions[1] = () => Console.Write(i);
        i = 2;
        actions[2] = () => Console.Write(i);
        i = 3;

        for (i = 0; i < 3; i++)
        {
            actions[i]();
        }        
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. A list of preprocessor commands available in C#
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables