I'm struggling to understand why it's okay to attach a 'normal' method as a subscriber to a publisher event, and also a delegate.
For example...
public class Caller
{
public string Name { get; set; }
public event EventHandler<RuedaEventArgs> MakeRuedaCall;
public virtual void OnMakeRuedaCall(RuedaEventArgs args) {
if (MakeRuedaCall != null) {
MakeRuedaCall(this, args);
}
}
}
This is my publisher class where I define and raise the event. I'm also making use of some custom event arguments.
public class Salsera {
public Salsera(Caller caller) {
caller.MakeRuedaCall += MakeMovement;
}
public void MakeMovement(object source, RuedaEventArgs args) {
if (args.CallName == "Vacilala") {
Turn();
}
if (args.CallName == "Patin") {
MoveToOutside();
}
}
private void MoveToOutside() {
Console.WriteLine("Ladies move to the outside....");
}
private void Turn() {
Console.WriteLine("Ladies turn....");
}
}
This is a class where I add a method as a subscriber to the event in the constructor.
Suppose I then have somewhere else...
Caller matt = new Caller();
EventHandler<RuedaEventArgs> anonyMouseFunc = (sender, eventArgs) =>
{
switch (eventArgs.CallName) {
case "Patin":
Console.WriteLine("Adding a new subscriber for Patin");
break;
case "Vacilala":
Console.WriteLine("Adding a new subscriber for Vacilala");
break;
}
};
matt.MakeRuedaCall += anonyMouseFunc;
Sorry if this seems like a silly question but why is it that you can subscribe a 'normal' method (assuming it matches the delegate signiture) to an event, and also an anonymous method as a delegate to an event.
i.e. how does public event EventHandler<RuedaEventArgs> MakeRuedaCall;
handle both options?
Many thanks,
Sorry if this seems like a silly question but why is it that you can subscribe a 'normal' method (assuming it matches the delegate signiture) to an event, and also an anonymous method as a delegate to an event.
You're subscribing a delegate in both cases. In this case:
caller.MakeRuedaCall += MakeMovement;
... you're using a method group conversion to convert MakeMovement
(which is a method group in spec terminology) into a delegate instance. That code is (almost entirely) equivalent to:
caller.MakeRuedaCall += new EventHandler<RuedaEventArgs>(MakeMovement);
Or to think of it another way, it's equivalent to:
EventHandler<RuedaEventArgs> handler = MakeMovement;
caller.MakeRuedaCall += handler;
This ability to create delegates from regular methods isn't just for event handling, of course - you can use it for LINQ and anywhere else you use delegates, too.
See more on this question at Stackoverflow