Search code examples
c#winformslistviewevent-handlingcontextmenustrip

Is passing an EventArg around event handlers potentially dangerous?


I'm calling an event handler from another one:

private void launchApplicationToolStripMenuItem_Click(object sender, EventArgs e) {
            listApplications_DoubleClick(listApplications, null); 
        }

        private void listApplications_DoubleClick(object sender, EventArgs e) {

"listApplications" is a ListView.

I had to pass listApplications because I cast sender in the DoubleClick() event to a ListView.

What about the second arg, though? Should I pass null, as shown above, or should I pass "e" like so:

listApplications_DoubleClick(listApplications, e);

Both ways work fine/identically under good circumstances. I don't know if that would be the case if there were an exception, though...


Solution

  • Well, I wouldn´t exactly say dangerous, but it can cause some problems, such as exceptions if not properly handled. In your example, one event is a click event and the other is a double click event, that implies that both the EventArgs object, e, are in fact a MouseEventArgs. Which is good, cause then you don´t have to worry about the second event handler accessing inexistent members of e.

    Now let´s suppose you want to call the paint event whenever the user clicks on a button, for instance. In that case the click event then will call the paint event. Now the problem is: the paint event expects a PaintEventArgs, so passing a MouseEventArgs could cause an exception. Of course, if you´re in control of both pieces of code then you can check for yourself to see if there will be any access to a PaintEventArgs specific member. If not, then you´re fine, although I do not see the point of passing the args anyways in this scenario.

    Hope that wasn´t too confusing.