Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

eventargs

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.

like image 791
xbonez Avatar asked Dec 21 '22 18:12

xbonez


2 Answers

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;
    }
like image 139
Reed Copsey Avatar answered Jan 05 '23 00:01

Reed Copsey


Shouldn't your event handler be declared like this:

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

?

like image 33
Kirk Woll Avatar answered Jan 04 '23 23:01

Kirk Woll