Sign in to follow this  
Timptation

C# event question

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this