How to do I return an item from a custom event handler

873 Views Asked by At

A project I'm working on requires me to be able to fire off an event everytime an item is added to a list. To achieve this, I created a custom List class inheriting from List and added a OnAdd event. I also want to return the item being added as EventArgs for which I added some more code (given below):

    public class ClientListObservable<Client>:List<Client>
    {
        public event EventHandler<EventArgs<Client>> OnAdd;

        public void Add(Client item)
        {
            if (null != OnAdd)
            {
                OnAdd(this, new EventArgs<Client>(item));
            }

            base.Add(item);
        }
    }

    public class EventArgs<Client> : EventArgs
    {
        public EventArgs(Client value)
        {
            m_value = value;
        }

        private Client m_value;

        public Client Value
        {
            get { return m_value; }
        }
    }

This is how I add a handler

clientList.OnAdd += new EventHandler<EventArgs<Client>>(clientList_OnAdd);

But, in the OnAdd method:

private void clientList_OnAdd(object sender, EventArgs e)
        {
            //want to be able to access the data members of the Client object added
        }

I can only access e.Equals, e.GetHashCode, e.GetType and e.ToString, and none of the members of Client class.

4

There are 4 best solutions below

1
On BEST ANSWER

Change your event args to:

public class ClientEventArgs : EventArgs
{
    public ClientEventArgs(Client value)
    {
        m_value = value;
    }

    private Client m_value;

    public Client Value
    {
        get { return m_value; }
    }
}

Then:

    private void clientList_OnAdd(object sender, ClientEventArgs e)
    {
        Client client = e.Value;
    }
0
On

you should derive your custom class from EventArgs and have a member to host your custom objects in there, then you should invoke the event passing such specialized EventArgs which you would have created and initialized as needed.

2
On

Shouldn't your event handler be declared like this:

private void clientList_OnAdd(object sender, EventArgs<Client> e)

?

0
On

Create your own event args that extends EventArgs and has a public property of a "Client" object. Then on add populate the custom EventArgs with the new item and return it.