NeatNit
NeatNit

Reputation: 632

VB-like Custom Events in C#

Visual Basic has custom events. An example of custom events: https://msdn.microsoft.com/en-us/library/wf33s4w7.aspx

Is there a way to create a custom event in C#?

In my case, the main reason I need to create one is to have code run when the event is first subscribed to, which currently seems to be impossible.

For example, let's say I have a button. I want this button to be disabled (greyed out) if there are no subscribers, and enabled as soon as there is at least one subscriber. Theoretically, I would be able to do it like this - if this syntax actually existed:

// internal event, used only to simplify the custom event's code
// instead of managing the invocation list directly
private event Action someevent;

// Pseudo code ahead
public custom event Action OutwardFacingSomeEvent
{
    addhandler
    {
        if (someevent == null || someevent.GetInvocationList().Length == 0)
            this.Disabled = false;
        someevent += value;
    }
    removehandler
    {
        someevent -= value;
        if (someevent == null || someevent.GetInvocationList().Length == 0)
            this.Disabled = true;
    }
    raiseevent()
    {
        // generally shouldn't be called, someevent should be raised directly, but let's allow it anyway
        someevent?.Invoke();
    }
}

If I understand the VB article correctly, this code line-for-line translated into VB, would do exactly what I want. Is there any way at all to do it in C#?

In other words/a slightly different question: is there a way to run code on subscription and un-subscription of an event?

Upvotes: 1

Views: 77

Answers (1)

RBT
RBT

Reputation: 25877

You can take over the subscription process of an event by defining explicit event accessors in C# as well. Here’s a manual implementation of the someevent event from your example:

private Action someevent; // Declare a private delegate

public event Action OutwardFacingSomeEvent
{
    add 
    { 
       //write custom code
       someevent += value; 
    }
    remove 
    { 
         someevent -= value; 
         //write custom code
    }
}

Upvotes: 4

Related Questions