I have a simple question about Events. Now I have just read this article: http://www.c-sharpcorner.com/UploadFile/Ashush/DelegatesInCSharp02252008143634PM/DelegatesInCSharp.aspx
The article contains the following snippet of code as an example of how an event is coded. My question is this: Why not just bypass declaring an "Event" altogether and just have a delegate? Instead just have code that says: "if this delegate is referencing a function (i.e. not equal to null) then execute the function that it's pointing to. Why the extra layer here?
namespace EventsInCSharp
{
public class MyClass
{
public delegate void MyDelegate(string message);
public event MyDelegate MyEvent;
//this method will be used to raise the event.
public void RaiseEvent(string message)
{
if (MyEvent != null)
MyEvent(message);
}
}
class Program
{
static void Main(string[] args)
{
MyClass myClass1 = new MyClass();
myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);
Console.WriteLine("Please enter a message\n");
string msg = Console.ReadLine();
//here is we raise the event.
myClass1.RaiseEvent(msg);
Console.Read();
}
//this method will be executed when the event raised.
static void myClass1_MyEvent(string message)
{
Console.WriteLine("Your Message is: {0}", message);
}
}
}