• Advertisement
Sign in to follow this  

C# event question

This topic is 2859 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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...

Share this post


Link to post
Share on other sites
Advertisement
Yup; sounds like you've got the jist of it.

It looks like you've pretty much answered your own question ;)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement