Click here to Skip to main content
15,903,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i just found a piece(not enought to find it out) of code and i'm wondering how i can do this, because it's much better than a normal event in my case
C#
console.BindCommand("!", delegate(GameTime gameTime, string[] args)
            {
                console.WriteLine(args[0]);
            });

a simple example of how it looks.
so this will be runned if my class detects that the user wrote "!"

thanks for the help :)
Posted

It's all you need. The delegate is an anonymous method. So, you use this syntax to create inline events. The real advantage is, any variables in the method that creates this, are visible to the delegate. Google anonymous methods if you need more help.

I should add, this runs no faster or slower than an externally defined delegate method.
 
Share this answer
 
v2
Hi, Christian is absolutely right, and an event definition can be even simpler using Lambda form in .NET 4.0:
//'SomeControl' stands for any control that exposes a 'KeyDown' event
SomeControl.KeyDown += (sndr,eArgs)=>{MessageBox.Show(eArgs.KeyCode.ToString());};
In this example, you define the event while attaching it at the same time via Lambda.

Suggest you read Jon Skeet's "C# in Depth" (Manning Press) to get a great explanation of all the developments in the area of events, delegates in .NET C#.
 
Share this answer
 
post-script:

Anooop Madhusudanan, author of the excellent 'AmazedSaint's Tech #Journal' blog[^], has published an excellent collection of his essays on-line, that does a great job of reviewing the history of 'events' in .NET:

http://www.scribd.com/doc/53728207/Revisting-C-V1-0

He demonstrates very clearly different ways of writing events as newer versions of .NET has introduced Lambdas, etc.

best, Bill
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900