Why is the button click using an event...
Why doesn't it just invoke a delegate instead...
As we can see from #3 a delegate is instantiated when we are using an event. As seen in #4 this delegate instance is then "added" to an event. At line #5 we see how the event is fired; looking again at #3 and #4 I think that the event invokes the delegate which calls the onstartEvent method.
Looking again at #3 and #4 and then at #6 after running this code we see that we get get the exact same behaviour from invoking the delegate instance as from fireing the event.
1) Why are there events?
2) Furthermore looking at #0 things start to look a bit strange. An event is some type that is actually a delegate type. What ARE events, RELLY?
3) Why can't we just settle for delegates (Invoking delegates instead of firing events)
and be done with the events?
4) At #2 the delegate (?) EventHandler is added to an event. Where IS the event (where is it declared and instansiated)?
5) How is the event above called/invoked/fired
Regards
/Jens
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
// custom delegate
public delegate void StartDelegate();
// custom event
public event StartDelegate StartEvent; //#0
public Form1()
{
// Creating a button from code, otherwise the EventHandler delegate
// assignment is done automatically for us in the Form1.Designer.cs
Button clickMe = new Button();
clickMe.Text = "Click Me";
clickMe.Parent = this;
// An EventHandler delegate is assigned
// to the button's Click event
//clickMe.Click += new EventHandler(onclickMeClicked);
//
// We can just as well do it this way in order
// to make the similarities between events and delegates
// more obvious.
EventHandler eHandler = onclickMeClicked; //#1
clickMe.Click += eHandler; //#2
// our custom "StartDelegate" delegate is assigned
// to our custom "StartEvent" event.
//StartEvent += new StartDelegate(onstartEvent);
//
// We can just as well do it this way in order
// to make the similarities between events and delegates
// more obvious.
StartDelegate sDelegate = onstartEvent; //#3
StartEvent += sDelegate; //#4
// fire our custom event
StartEvent(); //#5
// Invokation of the delegate.
sDelegate(); //#6
// Replacing the method in the delegate.
sDelegate = AMethod;
// Invokation of the delegate.
sDelegate();
}
// this method is called when the "clickMe" button is pressed
public void onclickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("You Clicked.");
}
// this method is called when the "StartEvent" Event is fired
public void onstartEvent()
{
MessageBox.Show("Started event.");
}
// This method called when the "sDelegate" sd is invoked the second time.
public void AMethod()
{
MessageBox.Show("Delegate invokation.");
}
}
}
This post has been edited by jens: 22 January 2012 - 02:08 PM

New Topic/Question
Reply



MultiQuote








|