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);
Call an event handler using AddHandler Make sure the event is declared with an Event statement. Execute an AddHandler statement to dynamically connect the event-handling Sub procedure with the event.
Event handlers in C# An event handler in C# is a delegate with a special signature, given below. The first parameter (sender) in the above declaration specifies the object that fired the event. The second parameter (e) of the above declaration holds data that can be used in the event handler.
EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.
To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.
TF: if an event occurs and there is not event handler to respond to that event, the event ins ignored.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With