Anonymous method trivia


Consider the following C# 2.0 code:

using System.Windows.Forms;

class form:Form
{
form()
{
int msg=100;
Button b=new Button();
b.Text=”click”;
b.Click += delegate{MessageBox.Show(“now the value is:”+msg);};
Controls.Add(b);
Load += delegate{msg=200;};
msg=500;
}
static void Main(){Application.Run(new form());}
}

Questions:

a) What is displayed on the screen after the click?
b) Why?
c) Which are your assumptions?

d) How would you change you answers if the variable msg is of type global::System.String?


Which are your answers for the following code:

using System.Windows.Forms;
using System.Text;

class form:Form
{
 form()
 {
  StringBuilder msg=new StringBuilder("100");
  Button b=new Button();
  b.Text="click";
  b.Click += delegate{MessageBox.Show("now the value is:"+msg);};
  Controls.Add(b);
  Load += delegate{msg.Append("200");};
  msg.Append("500");
 }
 static void Main(){Application.Run(new form());}
}


Comments (1)

  1. INeedADip says:

    "now the value is 200".

    Assuming that the form is instantiated before the Load event is fired, and the ‘msg’ variables are the "same".  I don’t know that much about Anonymous methods, I don’t know if it’s like JavaScript where they have access to the same ‘msg’ variable one scope up.