Trick in C# with lambda and event

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow