I currently have 2 WinForms.
FormA creates an instance of FormB. I call the ShowDialog() method of FormB.
FormB defines public event Action<SomeClass, string> Analyze
When I click the ProcessEvent button of FormB I do the following:
Action<SomeClass, string> tempAction = Analyze;
if (tempAction != null)
{
tempAction.Invoke(instanceOfSomeClass, someString);
}
But the event is not invoked because tempAction is null.
Why would it be null?
I define events in the same way in FormA and they work fine.
EDIT:
I have a presenter class that subscribes to the event:
formBInstance.Analyze += StartAnalyze
you must sign for event. If there is no subsribers Analyze will be null
FormB form = new FormB();
form.Analyze += OnAnanlyze; // define callback function
Others have answered your original question. I'm just going to add some points that you should consider.
Event initializer
First of all, you can use `delegate {}´ as a initializer for all events to be able to skip the null check and also to make your events thread safe.
Example:
public class MyClass
{
public event EventHandler<TempActionArgs> TempAction = delegate {};
}
In that way you can invoke it by just using
TempAction(this, new TempActionArgs(someStrings);
No need for any checks.
Using the standard event mechanism
Don't use Action<>
for events. Do use the standard EventHandler
/EventArgs
mechanism to make your application to look like any other .NET application. imho Action<>
should only be used for temp invocation (and not during a objects lifetime). The LINQ methods are a perfect example.
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