Himanshu Mange
Himanshu Mange

Reputation: 184

Confusion regarding lambda expression C#

reference Removing FrameworkElements on Animation Completion

In above question, how come we access 'myrect' in lambda expression but can't access in traditional method.

lambda expression :

SB.Completed += (s,e) => myCanvas.Children.Remove(myRect);

traditional approach :

public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            lastFire = DateTime.Now;
        }

        DateTime lastFire;

        private void myCanvas_MouseMove(object sender, MouseEventArgs e)
        {
            DateTime nowTime = DateTime.Now;
            TimeSpan T = nowTime.Subtract(lastFire);

            if (T.TotalMilliseconds > 200)
            {
                lastFire = nowTime;
                Random Rand = new Random();

                Rectangle myRect = (Rectangle)FindResource("MyRect");
                myRect.Fill = new SolidColorBrush(Color.FromRgb((byte)Rand.Next(256), (byte)Rand.Next(256), (byte)Rand.Next(256)));
                Point myLoc = e.GetPosition(myCanvas);
                Canvas.SetLeft(myRect, myLoc.X - 10);
                Canvas.SetTop(myRect, myLoc.Y - 10);
                myCanvas.Children.Add(myRect);

                Storyboard SB = (Storyboard)FindResource("GrowSquare");
                SB.Completed += new EventHandler(SB_Completed);
                SB.Begin(myRect);
            }

        }

        void SB_Completed(object sender, EventArgs e)
        {
            myCanvas.Children.RemoveAt(0);
        }
    }

Upvotes: 2

Views: 112

Answers (1)

Twenty
Twenty

Reputation: 5961

As soon as you create a lambda expression the compiler will convert it to a class with the 'method' you created and fields for all the captured variables in the lambda expression. See this talk from David Wengier if you are interested.

So lets take the following code:

public void Foo()
{
   string bar = "Bar";
   Action action = x => Console.WriteLine(bar);
   action();
}

It will convert it to something like the following:

private sealed class Helper {

  public string bar;

  public void action()
  {
     Console.WriteLine(bar);
  }
}

And in your "traditional" method your variable myrect would be out of scope. What are scopes?

Upvotes: 2

Related Questions