Anybody know why this is not possible?
If the event is just a MulticastDelegate instance you should be able to reference it in the code. the compiler says EventA can only be on left side of -= or +=.
public delegate void MyDelegate();
public event MyDelegate EventA;
public void addHandlerToEvent(MulticastDelegate md,Delegate d){
md+=d;
}
///
addHandlerToEvent(EventA,new MyDelegate(delegate(){}));
An event is not a multicast delegate, just like a property is not a field.
C#’s
eventsyntax wraps multicast delegates to make life easier by providing syntactic sugar for adding and removing handler delegates. Your event definition would be compiled to the following:The
addandremovemethods within the expanded event definition are then called when you useoperator +=andoperator -=on the event.This is done in order to hide the internals of the multicast delegate, but expose a simple way to implement publishing/subscribing to events. Being able to get the underlying delegate (outside of the class where it’s defined) would break that intentional encapsulation.