ghassan_khadra
New member
- Joined
- Jun 13, 2021
- Messages
- 1
- Programming Experience
- 1-3
mouse.onRightClick += (Vector3 vector) => { Toggle Lock(); };
Click
event of a Button
, the "traditional" way to do that would be to start with a method that had the appropriate signature and performed the action you wanted:private void SayHello(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
Click
event of a Button
like so:var btn = new Button();
btn.Click += SayHello;
+=
operator to add a delegate to a method with the appropriate signature. If you were to create a WinForms app and double-click a Button
to generate a Click
event handler, you'd find code like that in the designer code file. The part on the right is known as a method group. Basically, using the name of the method alone, without parentheses, creates a delegate for that method, i.e. an object that contains a reference to that method. You can then pass that object around and anywhere you have a reference to it, you can invoke the method it refers to, even if you don't have a reference to the object that the method is a member of. That's the point of delegates: to allow you to invoke a method without having to care where that method is declared. In this case, when the Button
raises its Click
event, it can invoke the handlers for that event via those delegates and doesn't have to care where the methods themselves are declared.var btn = new Button();
btn.Click += (sender, e) => { MessageBox.Show("Hello"); };
var btn = new Button();
btn.Click += (sender, e) => MessageBox.Show("Hello");
object
named sender
and an EventArgs
named e
makes it look more like Java or JavaScript than C#. You don't have to stick to that convention in C# but you absolutely should.