I implemented a class similar to this interface:
[ImmutableObject(true)]
public interface ICustomEvent
{
void Invoke(object sender, EventArgs e);
ICustomEvent Combine(EventHandler handler);
ICustomEvent Remove(EventHandler handler);
ICustomEvent Combine(ICustomEvent other);
ICustomEvent Remove(ICustomEvent other);
}
This CustomEvent class works the same as MulticastDelegate. It can be called. It can be combined with another CustomEvent. And CustomEvent can be removed from another CustomEvent.
Now I want to declare the class as follows:
class EventProvider
{
public event CustomEvent MyEvent;
private void OnMyEvent()
{
var myEvent = this.MyEvent;
if (myEvent != null) myEvent.Invoke(this, EventArgs.Empty);
}
}
Unfortunately, this code does not compile. The compiler error CS0066 will appear:
"EventProvider.MyEvent": the event must be a delegate type
Basically, I need a property in which there is add and remove , and not get and set , I think the only way to use this keyword is event . I know that one obvious alternative is to declare two methods that will add and remove, but I also want to avoid this.
Does anyone know if there is a good solution to this problem? I wonder if there is a way to trick the compiler to accept a type without a delegate as an event. Custom attribute, possibly.
By the way, someone asked a similar question at expert-exchange.com. Since this site is not free, I do not see the answers. Here is the topic: http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_21697455.html