Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression and Messagebox in C#

private void SimpleLambda()
{
  dynamic showMessage =  x => MessageBox.Show(x);

  showMessage("Hello World!");
}

The Error message is : Can't convert lambda expression to dynamic type , because it is not a delegate type

Any help,

like image 921
KekoSha Avatar asked Aug 22 '13 13:08

KekoSha


3 Answers

This has nothing to do with MessageBox - as the error message says, you simply can't convert a lambda expression to dynamic as the compiler has no idea what delegate type to create an instance of.

You want:

Action<string> action = x => MessageBox.Show(x);

Or even use a method group conversion, although then you have to match the return type:

Func<string, DialogResult> func = MessageBox.Show;

You can then use dynamic if you want:

dynamic showMessage = action; // Or func
showMessage("Hello World!");

Alternatively, you can specify the lambda expression in an explicit delegate instance expression:

dynamic showMessage = new Action<string>(x => MessageBox.Show(x));
like image 198
Jon Skeet Avatar answered Oct 07 '22 13:10

Jon Skeet


private void SimpleLambda()
{
  Action<string> showMessage =  x => MessageBox.Show(x);

  showMessage("Hello World!");
}
like image 29
speti43 Avatar answered Oct 07 '22 13:10

speti43


You have to declare the delegate type. Otherwise it won't know what type of lambda expression it's supposed to be—x could be anything. This should work:

Action<string> showMessage = x => MessageBox.Show(x);

See Action<T> for clarification on what this delegate type is.

like image 22
p.s.w.g Avatar answered Oct 07 '22 13:10

p.s.w.g