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?
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.
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.
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.
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.
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