10

I have an event handler method that's called directly as a standard method. That is, it's not only called when my event occurs but also just as a private method.

UtilStk.StkRoot.OnStkObjectAdded += new 
    IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);

private void TallyScenarioObjects(object sender)
{
    ...
}

Is it suitable to pass a null argument when calling this handler directly?

TallyScenarioObjects(null);
wulfgarpro
  • 6,666
  • 12
  • 69
  • 110
  • as long as your event handler handles the null value – Kris Ivanov Jan 31 '11 at 22:45
  • 1
    See also http://stackoverflow.com/questions/4684513/how-to-trigger-a-timer-tick-programatically/4684566#4684566 - directly calling event handlers like this is a code smell. – Bevan Jan 31 '11 at 22:48

3 Answers3

18

Just encapsulate the common logic into another method that can be called from your event handler:

UtilStk.StkRoot.OnStkObjectAdded += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);

private void TallyScenarioObjects(object sender)
{
    DoStuff();
}

private void DoStuff() { ... }

private void AnotherMethod()
{
    DoStuff();
}

That said, your handler is a method, there's nothing special about it, so you could always dummy up arguments and call it directly. I wouldn't go that route though.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
7

Yes that would work, but it would be better practice to have a 2nd method that could be called directly or from the event handler:

UtilStk.StkRoot.OnStkObjectAdded += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);

private void TallyScenarioObjects(object sender)
{
     DoTally(....);
}

private void DoTally(....)
{
}

If nothing else you won't confuse other developers who won't be expecting to see an event handler called that way.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
1

I agree with the rest. Have your event call a method. Then you can invoke that method from wherever you'd like.

UtilStk.StkRoot.OnStkObjectAdded += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);

private void TallyScenarioObjects(object sender)
{
    MyMethod();
}

private  void MyMethod()
{
    //Code here.
}