This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why delegate(0)
accomplishes this, in the kind of simple terms I can understand.
xmpp.OnLogin += delegate(object o) {
xmpp.Send(new Message(new Jid(JID_RECEIVER),
MessageType.chat,
"Hello, how are you?"));
};
It serves as an anonymous method, so you don't need to declare it somewhere else. It's very useful.
What it does in that case is to attach that method to the list of actions that are triggered because of the
onLogin
event.That is creating an anonymous function. This feature was introduced in C# 2.0
Agreed with Abe, this is an anonymous method. An anonymous method is just that -- a method without a name, which can be supplied as a parameter argument.
Obviously the OnLogin object is an Event; using an += operator ensures that the method specified by the anonymous delegate above is executed whenever the OnLogin event is raised.
Basically, the code inside the {} will run when the "OnLogin" event of the xmpp event is fired. Based on the name, I'd guess that event fires at some point during the login process.
The syntax:
is a called an anonymous method. The code in your question would be equivilent to this:
You are subscribing to the OnLogin event in xmpp.
This means that when xmpp fires this event, the code inside the anonymous delegate will fire. Its an elegant way to have callbacks.
In Xmpp, something like this is going on:
OnLogin
on xmpp is probably an event declared like this :where
LoginEventHandler
is as delegate type probably declared as :That means that in order to subscribe to the event, you need to provide a method (or an anonymous method / lambda expression) which match the
LoginEventHandler
delegate signature.In your example, you pass an anonymous method using the
delegate
keyword:The anonymous method matches the delegate signature expected by the
OnLogin
event (void return type + one object argument). You could also remove theobject o
parameter leveraging the contravariance, since it is not used inside the anonymous method body.