Assigning code to a variable

You could assign it to an Action like this:

var ButtonClicked = new Action(() => MessageBox.Show("hi"));

Then call it:

ButtonClicked();

For completeness (in regards to the various comments)…

As Erik stated, you could execute multiple lines of code:

var ButtonClicked = new Action(() =>
{
    MessageBox.Show("hi");

    MessageBox.Show("something else");  // something more useful than another popup ;)
});

As Tim stated, you could omit the Action keyword

Action ButtonClicked = () => MessageBox.Show("hi");

Action ButtonClicked = () =>
{
    // multiple lines of code
};

To address KRyan’s comment, regarding the empty parentheses, that represents the list of parameters you want to be able to send to the Action (in this case, none).

If, for instance, you wanted to specify the message to show, you could add “message” as a parameter (note that I changed Action to Action<string> in order to specify a single string parameter):

Action<string> ButtonClicked = (message) => MessageBox.Show(message);

ButtonClicked("hello world!");

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)