Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trick in C# with lambda and event

Tags:

c#

lambda

events

I'm trying to figure out if there is a way to accomplish something like this:

Button button = new Button() { OnClick += (sender, e) => MessageBox.Show("hello") };

But it doesn't want to work :D I want to create a control and to add one event to it at the same time. Is it possible?

like image 917
Patryk Golebiowski Avatar asked Dec 19 '22 06:12

Patryk Golebiowski


1 Answers

No, object initializers don't allow you to attach event handlers, unfortunately.

The C# team is aware of this limitation - there was some hope that this would be in C# 6, but the feature was dropped. I hope it was dropped due to a lack of time rather than to really lose the feature - maybe we'll see it in C# 7.

like image 145
Jon Skeet Avatar answered Jan 06 '23 16:01

Jon Skeet