473,416 Members | 1,725 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,416 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 2588

"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,
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
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...
23
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...
9
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...
1
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...
5
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...
22
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...
17
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...
3
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...
24
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.