C# event question

Started by
4 comments, last by Timptation 13 years, 11 months ago
Can an event only be "fired" from the class it belongs to? I have the following main() which exists in a separate class from "myClass": myClass classInstance = new myClass(); classInstance.testEvent += new testDelegate(classInstance.sayHi); classInstance.testEvent(); and I end up withe the error: Error 1 The event 'ConsoleApplication2.myClass.testEvent' can only appear on the left hand side of += or -= (except when used from within the type 'ConsoleApplication2.myClass') So it doesn't like the third line, but if I make a function within myClass that just calls testEvent() and use that, then everything is fine...
Advertisement
Yup; sounds like you've got the jist of it.

It looks like you've pretty much answered your own question ;)
Deep Blue Wave - Brian's Dev Blog.
I guess that's literally what the error is saying... it's just that I don't see why you shouldn't be able to fire a PUBLIC event in a public setting... Weird.
Because the 'event' keyword is specifically designed to prevent that behavior (among other things).

If you want to raise the delegate from outside the class itself, remove the event keyword and make it a regular multicast delegate, or create a public method to fire it.
Now if you want to have a fun experiment; try to fire an object's event from a different instance of the same class. Will it let you do that?
Deep Blue Wave - Brian's Dev Blog.
Yup, that was what I figured. Thanks for the heads up guys! Case closed. Oh, and BTownTKD, I created a member that took a reference to another myClass and fired it's event, and yes, that was allowed.

This topic is closed to new replies.

Advertisement