C# – array of events in C#

arraysc++events

basically:

public delegate void RecvCommandHandler (ChatApplication sender, byte[] content);
event RecvCommandHandler[] commands = new RecvCommandHandler[255];

I want to activate a different method/function for each command number, but I am really uncertain of the syntax. How am I supposed to do it?

I think I'll go with just an array of delegates for this one, but the question is still interesting.

Best Solution

You could create an array of a class with operator overloading to simulate the behavior you are interested in...

public delegate void EventDelegate(EventData kEvent);

public class EventElement
{
    protected event EventDelegate eventdelegate;

    public void Dispatch(EventData kEvent)
    {
        if (eventdelegate != null)
        {
            eventdelegate(kEvent);
        }
    }

    public static EventElement operator +(EventElement kElement, EventDelegate kDelegate)
    {
        kElement.eventdelegate += kDelegate;
        return kElement;
    }

    public static EventElement operator -(EventElement kElement, EventDelegate kDelegate)
    {
        kElement.eventdelegate -= kDelegate;
        return kElement;
    }
}

public EventElement[] commands = new EventElement[255];

commands[100] += OnWhatever;
commands[100].Dispatch(new EventData());
commands[100] -= OnWhatever;