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.
- private void button1_Click(object sender, EventArgs e)
-
{
-
// Then you write some code here
-
}
-
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.
- #region LogSystem events
-
public delegate void LogSystemDelegate(object sender, MyOwnNamespace.TextArgs e);
-
public event LogSystemDelegate LogMessage;
-
public void RaiseLog(string message)
-
{
-
LogSystemDelegate handler = LogMessage;
-
MyOwnNamespace.TextArgs Thelma = new MyOwnNamespace.TextArgs(DateTimeNow.ToString() + ":\t" + message);
-
if (handler != null)
-
{
-
if (handler != null)
-
{
-
handler(null, Thelma);
-
//Console.WriteLine(Thelma.Message);
-
}
-
}
-
}
-
#endregion
-
There are 3 primary parts to this code:
- The delegate that defines the event signature as an object and a custom TextArgs
- The event itself (note it does not need to define its arguments since the delegate did it)
- 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.
-
Subscribe all three methods to the one event
-
LogMessage += new LogSystemDelegate(WriteFile);
-
LogMessage += new LogSystemDelegate(DisplayLogEvent);
-
LogMessage += new LogSystemDelegate(SpeakMessage);
-
-
-
WriteFile(object sender, MyOwnNamespace.TextArgs e)
-
{
-
// Write to a text file
-
}
-
-
DisplayLogEvent(object sender, MyOwnNamespace.TextArgs e)
-
{
-
// Add the message to a listbox on screen
-
}
-
-
SpeakMessage(object sender, MyOwnNamespace.TextArgs e)
-
{
-
// Say the message out loud using the Text to Speach
-
}
-
Now whenever I need to log something in my code...
-
int x = 0; int y = 5;
-
string Yogi = "Picnic"; string Booboo = "basket";
-
RaiseLog("Done initializing");
-
-
int z = x+y;
-
string RangerSmith = Yogi + " " + Booboo;
-
RaiseLog("Done adding");
-