473,378 Members | 1,413 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Please give me more information about delegate and its usage?

Please give me more information about delegate and its usage?
Why do i use it and when?
Nov 19 '05 #1
3 2587

"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
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
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,

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

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:



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

"Rob Schieber" <sc******@hotmail.com> wrote in message
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Az Tech | last post by:
Hi people, (Sorry for the somewhat long post). I request some of the people on this group who have good experience using object-orientation in the field, to please give some good ideas for...
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application...
by: Edward | last post by:
Hello I hope someone could help me I'm trying to prevent code from running before the thread I created completes. Here's the code snippet DataTransformerWorker dtw = new...
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
by: tony | last post by:
I'm using PHP 5 on Win-98 command line (ie no web server involved) I'm processing a large csv file and when I loop through it I can process around 275 records per second. However at around...
by: rasiel | last post by:
I'm hoping someone can help me out. I'm a researcher in need of developing an automated database and would like to see if someone here is willing to consider putting together for me a simple...
by: Ron Adam | last post by:
I put together the following module today and would like some feedback on any obvious problems. Or even opinions of weather or not it is a good approach. While collating is not a difficult thing...
by: muler | last post by:
hi all, Can anyone explain (possibly with examples) any special uses of delegate combinations or removals? In the very simple example below all delegate combinations/removals can be done with...
by: =?Utf-8?B?U3dhcHB5?= | last post by:
Can anyone suggest me to pass more parameters other than two parameter for events like the following? Event: Onbutton_click(object sender, EventArgs e)" Event handler: button.Click += new...
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.