Search code examples
c#multithreadingudpeventhandler

EventHandler missing, don't know how to initialize


I just wanted to use the code from this thread (first post) to test something, I'm not really familiar with C#, but it crashed when a package is sent to the server at the following line:

NewMessageReceived(this, new MyMessageArgs(bytes));

with the following error message:

System.NullReferenceException: Object reference not set to an instance of an object

I think because NewMessageReceived is not initialized, but how do i do? Can anybody help me out? I can't find useful tips for EventHandlers in C#.

Thanks in advance.


Solution

  • An event must have at least 1 subscriber for you to raise it. Put a null check first before calling.

    if (NewMessageReceived != null)
    {
        NewMessageReceived(this, new MyMessageArgs(bytes));
    }