✅ The event can only appear on the left hand side of += or -=
Hello there, so I'm trying to change the getter/setter (adder/remover?) of my events. The events commented out is how they were originally and had no errors. When I changed the events to how they appear in the first image I'm getting the errors you see in my second image and I'm not sure why.
Thanks for the help.
Edit: These are both in the same class if that matters
11 Replies
Stack Overflow
C#: event with explicity add/remove != typical event?
I have declared a generic event handler
public delegate void EventHandler();
to which I have added the extension method 'RaiseEvent':
public static void RaiseEvent(this EventHandler self) ...
You need to fire backing delegate. When an event is declared as a field without add/remove, it behaves like a delegate you can invoke directly
I don't really understand what that means, but I'm invoking the backing variable instead and i'm not getting the error (but things are still getting subscribed to too many times so i'm not sure if it's working as intended)
Events themselves can't be invoked but when declared without add/remove it doubles as a delegate that can be invoked
so when I invoke the backing variable does any code in the public variable matter?
To the subscriber it appears they're subscribing to the event but it's actually subscribing to the backing delegate
add/remove just allow you to run things when being subbed or unsubbed
Like properties
I'm sorry I don't understand a lot of the language, but could you tell me if my code as I've changed it should work to prevent those events from being subscribed to multiple times? That's my main issue and I just can't understand if this is supposed to work or not
@wickedcat the Invoke and () syntax are only available on events when you have not overridden
add
and remove
because now the compiler has no idea what it should be calling
if you override those, you lose the ability to do MyEvent()
and MyEvent?.Invoke()
Ahh okay thank you, so I’ll have to find another workaround
yes, that workaround would be using the delegate field
but, also, your event is not bulletproof against having “duplicate” handlers (i am not quite sure what that means specifically)
and it is really the wrong way to solve this problem
what you should do is not add unwanted event handlers in the first place
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.