Why is my event throwing a null error?Ask Questions

 Posted on 20 days ago

For some reason my event is throwing a null error. I don't see anything wrong.

here is the event

public delegate void connectionSuccess(bool success);

public event connectionSuccess Connection;

 

then in a function i have this witch throws the null error

Connection(true);

 

Edit* function in another class that calls the connection function

Server.Connection += onConnection; Server.startConnection();

Share On: facebook gplus twitter
profile
Asked by Aidam Turner on 20 days ago Score: 50 points
Add Comment:

Comments

2 Answers

0 Corrected Answers
Aproved Answers
0
Profile
Answered by hardik chaudhary on 10/2/2019 11:21:44 AM Score: 542 points

You need to check and make sure something is actually subscribed to the event before you invoke it.

if(Connection != null) Connection(true);

Comments

Add Comment:
Aproved Answers
0
Profile
Answered by Steve Summit on 10/1/2019 9:10:39 AM Score: 35 points

If it is not connected, it is null.

Try this instead:

var h = Connection;

if ( h!=null ) {

     h(true);

}

 

I'm assigning to a (local) variable first in order to overcome multi-threading scenarios where there are modifications between checking for null and calling.

I.e. the following would not be thread-safe:

if ( Connection!=null ) {

        Connection(true); // Here, could already be null, again.

}

Comments

Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
Password
New Member?
Sign up and complete profile
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.