Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Action event null?

Tags:

c#

events

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
like image 339
Draco Avatar asked Dec 27 '22 17:12

Draco


2 Answers

you must sign for event. If there is no subsribers Analyze will be null

FormB form = new FormB();
form.Analyze += OnAnanlyze; // define callback function
like image 60
Stecya Avatar answered Jan 16 '23 14:01

Stecya


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.

like image 27
jgauffin Avatar answered Jan 16 '23 14:01

jgauffin