Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of events in C#?

Tags:

arrays

c#

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.

like image 341
Nefzen Avatar asked Jun 12 '09 14:06

Nefzen


3 Answers

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;
like image 173
Jason King Avatar answered Sep 29 '22 19:09

Jason King


There's really no concept of an array of events - it's like talking about an array of properties. Events are really just methods which let you subscribe and unsubscribe handlers. If you need to be able to do this by index, I suggest you just have a pair of methods. (AddCommandHandler(int, RecvCommandHandler) and RemoveCommandHandler(int, RecvCommandHandler)). That won't support the normal event handling syntactic sugar, of course, but I don't see that there's a lot of alternative.

like image 31
Jon Skeet Avatar answered Sep 29 '22 20:09

Jon Skeet


The other option is to specify and index in the delegate prototype and have one event handler that "delegates" to the others, e.g.:

public delegate void RecvCommandHandler (int id, ChatApplication sender, byte[] content);

// ...

private RecvCommandHandler[] internalhandlers;

public void MyCommandHandler(int id, ChatApplication sender, byte[] content)
{
    internalHandlers[id](id, sender, content);
}
like image 22
Mike Marshall Avatar answered Sep 29 '22 19:09

Mike Marshall