Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this delegate call doing in this line of code (C#)?

Tags:

c#

delegates

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?")); 
};
like image 623
Hank Fay Avatar asked Jan 25 '23 03:01

Hank Fay


2 Answers

It's exactly the same as

xmpp.OnLogin += EventHandler(MyMethod);

Where MyMethod is

public void MyMethod(object o) 
{ 
    xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); 
}
like image 192
juan Avatar answered Feb 11 '23 20:02

juan


As Abe noted, this code is creating an anonymous function. This:


xmpp.OnLogin += delegate(object o) 
   { 
      xmpp.Send(
         new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); 
   };

would have been accomplished as follows in older versions of .Net (I've excluded class declarations and such, and just kept the essential elements):


delegate void OnLoginEventHandler(object o);

public void MyLoginEventHandler(object o)
{
      xmpp.Send(
         new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); 
}

[...]

xmpp.OnLogin += new OnLoginEventHandler(MyLoginEventHandler);

What you're doing in either case is associating a method of yours to run when the xmpp OnLogin event is fired.

like image 31
Remi Despres-Smyth Avatar answered Feb 11 '23 19:02

Remi Despres-Smyth