Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException when triggering event

Tags:

Consider the following:

class Client {     public static event EventHandler connectFailed;      private Socket socket;      public Client()     {         socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);         IPEndPoint endpoint = new IPEndpoint(             IPAddress.Parse("192.168.1.100"),             7900             );          try         {             socket.Connect(endpoint);         }         catch(Exception e)         {             connectFailed(e, new EventArgs());         }     } } 

Assume the rest of the code is implemented (Event handlers and such in Program.cs).

I am running into an issue with NullRefrerenceException on the connectFailed(e, new EventArgs()); line, and I can't understand why. All my other events are firing just fine, and I don't see how this is any different.

Any ideas?

like image 761
Skudd Avatar asked Apr 23 '11 21:04

Skudd


People also ask

Why am I getting a NullReferenceException?

This error is caused when an object is trying to be used by a script but does not refer to an instance of an object. To fix this example we can acquire a reference to an instance of the script using GameObject.

What does system NullReferenceException mean?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.

Can NullReferenceException be caught?

Find out which exception you're receiving, and either catch that specific exception, or else prevent it from occurring in the first place. You should never catch NullReferenceException.


1 Answers

You need a null check - in C# you can't call events when there are no handlers registered on that event.

The normal thing would be to implement an OnConnectFailed method:

protected virtual void OnConnectFailed(e as EventArgs) {     EventHandler tmp = connectFailed;     if(tmp != null)         tmp(this,e); } 

Also, the first argument to the event handler should be this, not the exception. If you need to pass the exception to the event handler, create an EventArgs class with an exception property.

Also, there's no point in raising an event from the constructor... nothing has a chance to add a handler to it.

like image 134
Random832 Avatar answered Oct 06 '22 05:10

Random832