G
Guest
I have the following code to tie up a custom delegate (ConsoleDelegate) with
two methods from a separate class called CallMyEvents:
static void Main()
{
CallMyEvents call = new CallMyEvents();
ConsoleDelegate del += new ConsoleDelegate(call.FirstMethod);
del += new ConsoleDelegate(call.SecondMethod);
del();
}
By calling del(), both methods are called in turn.
In the CallMyEvents class I have also declared an event: public event
ConsoleDelegate myEvent;
I have a method to call the event:
public void OnMyEvent()
{
if(myEvent != null)
myEvent();
}
I changed the Main method to the following:
CallMyEvents call = new CallMyEvents();
call.myEvent += new ConsoleDelegate(call.FirstMethod);
call.myEvent += new ConsoleDelegate(call.SecondMethod);
Call.OnMyEvent();
Calling OnMyEvent also calls both methods in turn.
My question is, what is the difference between using just the delegate to
call the methods and tying the delegate to an event?
What are the benefits of using events rather than just delegates and what
restrictions are there if I just go with delegates.
If anyone could give me a simple answer I would be most grateful.
two methods from a separate class called CallMyEvents:
static void Main()
{
CallMyEvents call = new CallMyEvents();
ConsoleDelegate del += new ConsoleDelegate(call.FirstMethod);
del += new ConsoleDelegate(call.SecondMethod);
del();
}
By calling del(), both methods are called in turn.
In the CallMyEvents class I have also declared an event: public event
ConsoleDelegate myEvent;
I have a method to call the event:
public void OnMyEvent()
{
if(myEvent != null)
myEvent();
}
I changed the Main method to the following:
CallMyEvents call = new CallMyEvents();
call.myEvent += new ConsoleDelegate(call.FirstMethod);
call.myEvent += new ConsoleDelegate(call.SecondMethod);
Call.OnMyEvent();
Calling OnMyEvent also calls both methods in turn.
My question is, what is the difference between using just the delegate to
call the methods and tying the delegate to an event?
What are the benefits of using events rather than just delegates and what
restrictions are there if I just go with delegates.
If anyone could give me a simple answer I would be most grateful.