mountaindweller
mountaindweller

Reputation: 85

Lambda anonymous method in messagebox.show

I'm just playing with anonymous methods, and I was wondering why this code will not compile. Messagebox show takes a string, I'm trying to return it a string.

            MessageBox.Show(() => 
            {
                if (button1.Text == "button1")
                {
                   return "ok";
                }
                else
                {
                   return "not button1 text";
                }
            });

Cannot convert lambda expression to type string because it is not a delegate type.

Can someone explain why? Am I missing a cast?

Upvotes: 0

Views: 185

Answers (1)

msporek
msporek

Reputation: 1197

What your piece of code is doing is defining a Func that returns a string (Func<string>). And then you try to pass that Func<string> into MessageBox.Show as an argument. Please note that MessageBox.Show does not accept Func<string> type, it accepts string so you cannot pass lamda expression to it this way). But you could do like that:

Func<string> yourFunc = () => 
            {
                if (button1.Text == "button1")
                {
                   return "ok";
                }
                else
                {
                   return "not button1 text";
                }
            };

MessageBox.Show(yourFunc());

Upvotes: 8

Related Questions