By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,470 Members | 970 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,470 IT Pros & Developers. It's quick & easy.

Please give me more information about delegate and its usage?

P: n/a
Please give me more information about delegate and its usage?
Why do i use it and when?
Nov 19 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a

"Minh Khoa" <Mi******@discussions.microsoft.com> a écrit dans le message de
news: C4**********************************@microsoft.com...
Please give me more information about delegate and its usage?
Why do i use it and when?


Delegates are function pointers. Function pointers come in handy
whenever you need "callback" syntax (mostly UI and other asynchronous work).
They are not, strictly speaking, needed, since you could use functors
(classes carrying only virtual functions) instead, but that's a nice
addition to .Net.

Nov 19 '05 #2

P: n/a
Minh Khoa wrote:
Please give me more information about delegate and its usage?
Why do i use it and when?


You will use delegates primarily for creating Event Handlers and
Callback functions, or Asynchronous (Multithreaded) operations. For a
more detailed explanation, I would search for delegates on MSDN.

--
Rob Schieber
Nov 19 '05 #3

P: n/a
Let me elaborate a bit on Rob's reply. Delgates are a little difficult to
understand, and the documentation will take some re-reading to understand
(who knows, my explanation may take some re-reading as well!).

A delegate is a thread-safe, managed "function pointer." It is a class which
describes a signature for a function, and any class that inherits it must
define a method with the same signature. It doesn't look like a class when
you define one; it looks like a function that has no execution block. But it
is, in fact, a class. The rest of it is nicely hidden. A delegate looks like
this when you define it:

public delegate void myDelegate(object parameter1, string parameter2,
CustomType parameter3);

When you use a delegate, you create an instance of the class by defining a
function with the same signature. Example:

public void myFunction(object parameter1, string parameter2,
CustomType parameter3)
{
// do something
}

Note that this doesn't actually make the method the delegate yet. It simply
defines a function with the same signature as the delegate.

Now, let's say you have a method in another class which you want to perform
several different types of operations. You can pass a delegate to the
function and execute it. Since you can define multiple functions that take
the same parameters as the delegate, but do different things, this can make
the function in the other class do different things. Example:

public void doDifferentThings(myDelegate theFunction)
{
theFunction(this.SomeObject, this.SomeString,
this.SomeMemberOfCustomType);
}

So, whatever you define as the delegate function passed to this method
executes, and operates with the parameters passed to it in whatever way you
define.

As Rob mentioned, the most common use of delegates is with Events. A
delegate is the perfect way to define a non-specific Event Handler, as the
developer can plug in any functionality to handle the event that he/she
wishes. For example, in creating custom Exceptions, you might want to pass
information about the specific type of exception to an Event Handler, so you
create a derived EventArgs class. I'll show you one I created for sending
emails by a class hosted in a service. As the class is running unattended,
the service may want to do some logging when the class sends an email. So I
created an EventArgs class to hold information about the email sent, and a
delegate EventHandler for any class wishing to handle the event:

public class MailSentEventArgs : EventArgs
{
private DateTime _TimeSent;
public DateTime TimeSent
{
get { return _TimeSent; }
}

private MailMessage _Message;
private NetworkCredential _Credentials;

private MailSettings _Settings;
public MailSettings Settings
{
get { return _Settings; }
}

public MailAddress From
{
get { return _Message.From; }
}

public MailAddressCollection To
{
get { return _Message.To; }
}

public MailAddress ReplyTo
{
get { return _Message.ReplyTo; }
}

public MailAddressCollection CC
{
get { return _Message.CC; }
}

public MailAddressCollection BCC
{
get { return _Message.Bcc; }
}

public string Subject
{
get { return _Message.Subject; }
}

public string Body
{
get { return _Message.Body; }
}

public string CredentialsUserName
{
get { return _Credentials.UserName; }
}

public string CredentialsPassword
{
get { return _Credentials.Password; }
}

public string CredentialsDomain
{
get { return _Credentials.Domain; }
}

public MailSentEventArgs(DateTime timeSent, MailSettings settings,
MailMessage message, NetworkCredential credentials)
{
_TimeSent = timeSent;
_Settings = settings;
_Message = message;
_Credentials = credentials;
}
}

Note that this class contains both custom class instances, and platform
class instances. The members are all read-only; they can only be set when
creating an instance of the class. Now, the delegate EventHandler:

public delegate void MailSendEventHandler(object sender,
MailSentEventArgs args);

Next, in my MailClient class, I defined an event and a handler method for
the event:

/// <summary>
/// Event that sends information about the Mail Sent when it
is sent.
/// </summary>
public event MailSendEventHandler MailSent;

The above declares an event that is a MailSendEventHandler delegate. Next, I
defined a method to raise the Event:

/// <summary>
/// Raises the MailSent Event
/// </summary>
/// <param name="e">MailSentEventArgs</param>
protected void RaiseMailEvent(MailSentEventArgs e)
{
if (MailSent != null) MailSent(this, e);
}

As you can see, it checks to see whether there is an instance of the event
delegate defined first. Simply declaring the event delegate doesn't
instantiate it. It is instantiated when a client class wires up an Event
Handler method to it. This is why an EventHandler method must match the
signature of the EventHandler delegate defined for that event. Notice that
the event is of type MailSendEventHandler. This means that any function that
is executed to handle the event must match the signature of the
MailSendEventHandler delegate I described earlier.

The RaiseMailEvent() method calls the method that is assigned to that
delegate. To raise the event in my MailClient class, I simply create an
instance of MailSentEventArgs, populating it with information about the
email sent, and call the RaiseMailEvent method. The following snippet is
from a function in the same class that sends an email:

//...
client.SendAsync(message, DateTime.Now);
RaiseMailEvent(new MailSentEventArgs(DateTime.Now,
SmtpSettings, message, Credentials));
//...

Now a client class can wire up an EventHandler by defining a method that
matches the MailSendEventHandler delegate, and the MailClient class will
call that method using the RaiseMailEvent() method, which takes the delegate
instance as a parameter:

This is the client delegate method. It matches the signature of the
MailSentEventHandler delegate:

void client_MailSent(object sender, MailSentEventArgs args)
{
//...
}

Here, I wire up the MailClient.MailSent delegate to the method:

private void Form1_Load(object sender, EventArgs e)
{
client = new MailClient();
//...
client.MailSent += new MailSendEventHandler(client_MailSent);
//...
}

You may have noticed that an EventHandler delegate is assigned using "+=".
This is because .Net delegates are Multi-Cast delegates. That is, you can
actually wire up multiple methods to them. The methods assigned are executed
in the order in which they are assigned. This way, for example, more than
one client class can handle the same event, wiring up its own method to the
delegate Event Handler. So, rather than using "=" (which would replace any
methods already assigned), you use "+=" to add the method to the "queue" as
it were.

I hope this has given you a bit of a head start on this powerful, yet
complex topic. I recommend reading more on the subject, as I've only
scratched the surface of what delegates can do here. The following link will
return a number of good Microsoft MSDN references:

http://search.microsoft.com/search/r...&c=4&s=1&swc=4

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Big things are made up of
lots of little things.

"Rob Schieber" <sc******@hotmail.com> wrote in message
news:%2******************@TK2MSFTNGP10.phx.gbl...
Minh Khoa wrote:
Please give me more information about delegate and its usage?
Why do i use it and when?


You will use delegates primarily for creating Event Handlers and Callback
functions, or Asynchronous (Multithreaded) operations. For a more
detailed explanation, I would search for delegates on MSDN.

--
Rob Schieber

Nov 19 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.