I've been confused over the past weeks now about events. I understand how delegates work, not how it works in detail but enough to know that
delegate datatype
is a single cast delegate.
delegate void
is a multicast delegate - a list of references to methods.
I know a delegate type compiles to a class, but unfortunately I am still not sure how the method is referenced. For example
delegate void TestDelegate();
TestDelegate testDelegate = new TestDelegate(myObject.SomeMethod) ;
Question 1: I think myObject is the target, and SomeMethod is the method to reference, but I'm only passing one input. So is myObject.SomeMethod compiled to a string and is the string split by the period? Ridiculous I know.
Question 2: When you add to a multicast delegate
multicastdelegate+=newmethodtobereference
multicastdelegate() ;
Every method in the invocation list is called or notified?
If that's true, why the hell do I need events or the event
keyword? Is it simply to tell the developers that Hey, this is acting as an event? Because I'm seriously confused, I just want to move on at this stage lol. This is a sample code I wrote to test it today whether I need event keyword or not.
using System;
namespace LambdasETs
{
public delegate void IsEvenNumberEventHandler(int numberThatIsEven);
public class IsEvenNumberFound
{
public IsEvenNumberEventHandler IsEvenNumberEvent;
private int number;
public void InputNumber(int n)
{
if(number %2 ==0)
{
if (IsEvenNumberEvent != null)
{
IsEvenNumberEvent(n);
}
}
}
public static void Main()
{
IsEvenNumberFound isEvenNumberFound = new IsEvenNumberFound();
isEvenNumberFound.IsEvenNumberEvent += IsEvenNumberAction;
isEvenNumberFound.InputNumber(10);
Console.ReadLine();
}
public static void IsEvenNumberAction(int number)
{
Console.WriteLine("{0} is an even number!", number);
}
}
}
Adding the event keyword to the field public IsEvenNumberEventHandler IsEvenNumberEvent;
has no difference.
Please can some explain so that a noob can understand thanks.