473,320 Members | 2,052 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,320 software developers and data experts.

event or delegate?

Hi, what is the difference and where should I use event of delegate?
Thank u so much
Kr,
Jun 4 '09 #1
2 1153
Frinavale
9,735 Expert Mod 8TB
Events rely on Delegates to do what they do.

If you know anything about function pointers, delegates are Objects that pretty much server a function pointers (a pointer is a variable that contains a memory address...a function pointer is a variable that contains a memory address that is a function.)

Please take a look at this article on how to use events in .NET for more information.
Jun 5 '09 #2
tlhintoq
3,525 Expert 2GB
It's not a case of either/or... Delegates work with events.

A delegate is the signature of an event. I'm sure you've double-clicked on a button and Visual Studio was good enough to write the stub of your handler for you.

Expand|Select|Wrap|Line Numbers
  1.         private void button1_Click(object sender, EventArgs e)
  2.         {
  3.             // Then you write some code here
  4.         }
  5.  
The signature is that part that tells it the parameters: (object sender, EventArgs e)
Any method that matches the signature of the delegate can be used to receive the event.

Here is an example from my own code. It is a custom event used for the logging of messages.

Expand|Select|Wrap|Line Numbers
  1.         #region LogSystem events
  2.         public delegate void LogSystemDelegate(object sender, MyOwnNamespace.TextArgs e);
  3.         public event LogSystemDelegate LogMessage;
  4.         public void RaiseLog(string message)
  5.         {
  6.             LogSystemDelegate handler = LogMessage;
  7.             MyOwnNamespace.TextArgs Thelma = new MyOwnNamespace.TextArgs(DateTimeNow.ToString() + ":\t" + message);
  8.             if (handler != null)
  9.             {
  10.                 if (handler != null)
  11.                 {
  12.                     handler(null, Thelma);
  13.                     //Console.WriteLine(Thelma.Message);
  14.                 }
  15.             }
  16.         }
  17.         #endregion
  18.  
There are 3 primary parts to this code:
  1. The delegate that defines the event signature as an object and a custom TextArgs
  2. The event itself (note it does not need to define its arguments since the delegate did it)
  3. And a method that actually raises the event after checking that such a thing really exists. It also adds a timestamp to every log message.

This is how multiple methods can all subscribe to the same event.

Expand|Select|Wrap|Line Numbers
  1. Subscribe all three methods to the one event
  2. LogMessage += new LogSystemDelegate(WriteFile);
  3. LogMessage += new LogSystemDelegate(DisplayLogEvent);
  4. LogMessage += new LogSystemDelegate(SpeakMessage);
  5.  
  6.  
  7. WriteFile(object sender, MyOwnNamespace.TextArgs e)
  8. {
  9.    // Write to a text file
  10. }
  11.  
  12. DisplayLogEvent(object sender, MyOwnNamespace.TextArgs e)
  13. {
  14.    // Add the message to a listbox on screen
  15. }
  16.  
  17. SpeakMessage(object sender, MyOwnNamespace.TextArgs e)
  18. {
  19.    // Say the message out loud using the Text to Speach
  20. }
  21.  
Now whenever I need to log something in my code...

Expand|Select|Wrap|Line Numbers
  1. int x = 0; int y = 5;
  2. string Yogi = "Picnic"; string Booboo = "basket";
  3. RaiseLog("Done initializing");
  4.  
  5. int z = x+y;
  6. string RangerSmith = Yogi + " " + Booboo;
  7. RaiseLog("Done adding");
  8.  
Jun 5 '09 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Andy Read | last post by:
Hello all, I have the requirement to produce source code that produces an object hierarchy. Example: Root | Folder 1
5
by: Ian Richardson | last post by:
I'm writing some code which does one thing when onreadystatechange occurs, e.g. handle.onreadystatechange = function() { blah(handle,other_params) }; ....but sometimes I need to add another,...
1
by: emma middlebrook | last post by:
Hi I want to find out what objects are due to receive an event i.e. those that have added themselves as an event handler via +=. Yes, it's a little pointless perhaps (or can anyone give some...
18
by: Elder Hyde | last post by:
Hey all, A class of mine needs to tell the outside world when its buffer is not empty. The problem is that C# seems to force you to put the event-raising code in the base class. To illustrate,...
4
by: BC | last post by:
Hi all, Just wondering what are the difference between: public event EventHandler MessageNotify; public EventHandler MessageNotify; A friend told me it's related to the accessibility levels.
1
by: Kerry Jenkins | last post by:
I am having problems passing an Event Delegate as an argument to a method that accepts a delegate argument. I get the following error message: 'Public Event ProgressChanged(sender As Object, e...
13
by: Charles Law | last post by:
Mr "yEaH rIgHt" posted the following link about a week ago in answer to my question about removing event handlers. > http://www.vbinfozine.com/t_bindevt.shtml Following on from that post, the...
6
by: David Veeneman | last post by:
I have several events that pass a value in their event args. One event passes an int, another a string, another a DateTime, and so on. Rather than creating a separate set of event args for each...
22
by: dvestal | last post by:
Suppose I have this: class C { public delegate void MyEventHandler(); public event MyEventHandler MyEvent; public void foo() { MyEvent(); // NullReferenceException? } }
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: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
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...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
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 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.