If I have ClassA that has a public event, SomeEvent, and ClassC that has method, addListener, that accepts an EventHandler reference, why can't ClassB have a line that says c.addListener(ref a.SomeEvent)? If I try I get a compiler error that says: "The event 'ClassA.SomeEvent' can only appear on the left hand side of += or -= (except when used from within the type 'ClassA').
Why does this restriction exist? And how can I get around it while staying reasonably close to my structure?
I'm a C# newbie; any help would be appreciated. Thanks!
class ClassA {
public event EventHandler SomeEvent;
}
ClassB{
public ClassB() {
ClassA a = new ClassA();
ClassC c = new ClassC();
c.addListener(ref a.SomeEvent); //Compile error
}
}
class ClassC {
public void addListener(ref EventHandler handler) {
handler += onEvent;
}
private void onEvent(object sender, EventArgs e) {
//do stuff
}
}
Best Answer
Outside of the class, you only have access to the
add
andremove
accessors - that is the point of an event you can neither see other subscribers, nor change them (for example, setting the event to null). It would be better to handle the event normally, and cause whatever consequences you need.Imagine you could do what you suggest. For example, suppose you subscribe to a button click, and some other code uses that info to hook you into a "tick" event - you're code isn't going to work as it expected to = bug.
To make that explict; an event isn't an
EventHandler
, in the same way that a property isn't anint
- the event/property defines accessor methods.Re your scenario, either make
OnEvent
public and usea.SomeEvent += c.OnEvent;
, or have some similar method and use an anon-method: