I really don’t understand what is wrong with this code. It is throwing several errors:
error CS0079: The event
core.Events.Event.thisEventcan only appear
on the left hand side of+=or-=operatorerror CS0070: The event
core.Events.Event.thisEventcan only appear
on the left hand side of+=or-=when used outside of the type
core.Events.Eventerror CS1502: The best overloaded method match for
System.Delegate.Combine(System.Delegate, System.Delegate)has some
invalid argumentserror CS1503: Argument
#1cannot convertobjectexpression to type
System.Delegate
What am I doing wrong and how can I fix this?
using System;
using System.Runtime.CompilerServices;
namespace core.Events
{
public class Event
{
public delegate void EventDelegate (object from,EventArgs args);
public event Event.EventDelegate thisEvent {
[MethodImpl(MethodImplOptions.Synchronized)]
add {
this.thisEvent += (Event.EventDelegate)Delegate.Combine (this.thisEvent, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove {
this.thisEvent -= (Event.EventDelegate)Delegate.Remove (this.thisEvent, value);
}
}
public void call (object from, EventArgs args)
{
this.thisEvent (from, args);
}
}
}
Thank you in advance for your help I think I am just super tired and lost in source…
It is a similar kind of mistake as using the name of the property in the getter of the property. Which normally causes SO, this mistake is however caught early. You need to create a private backing field to store the delegate, the compiler no longer auto-generates it for you when you explicitly write the accessors. Thus:
Note the call() implementation, it avoids a crash if nobody subscribed the event and another crash when threads unsubscribe the event. And I used the short-cut notation to avoid calling Delegate.Combine() explicitly. Beware that this code isn’t actually different from what the compiler auto-generates if you don’t use accessors.