简体   繁体   中英

Variable causes NullReferenceException even though it's set

Maybe I'm doing something really wrong, but somehow this code always crashes with a NullReferenceException:

public class IncomingMessageEventData : EventArgs
{
    public IncomingMessageEventData(SpecialClasses.IncomingMessageData _msg, List<string> _toreturn)
    {
        msg = _msg;
        ToReturn = _toreturn;
    }
    public SpecialClasses.IncomingMessageData msg { get; set; }
    public List<string> ToReturn { get; set; }
}
public delegate void IncomingMessageHook(IncomingMessageEventData Args);
public event IncomingMessageHook InComingMessage;
public string NewMessage(string[] _message, System.Net.IPEndPoint RemoteIP)
{
    if (InComingMessage != null)
    {
        IncomingMessageEventData data = new IncomingMessageEventData(new SpecialClasses.IncomingMessageData(_message, RemoteIP), new List<string>());
        string ToReturn = "";
        InComingMessage(data);
        foreach (var item in data.ToReturn)
        {
if (item.Length > 0)
    ToReturn = item;
        }
        return ToReturn;
    }
    else return null;
}

There's 2 methods hooking to the event simultaneously, can that be the cause? If so, how do I avoid it? Or is passing a ref List just not the way to get values from a hooked method?

Thanks!

Edit: updated the code. Which works now! ... I think I know what I did wrong though.

See, the program this is part of uses plugins which it loads through Reflection, And there might have been the slightest possibility that I forgot to copy the updated plugin dll to the plugin directory before debugging. .. . hehe. ^^; Sorry! But at least my code uses best practices now ;P So many thanks for that one and I'll mark it as answer!

There are multiple problems here.

Passing a List<T> as a ref parameter is not a good approach. The List<T> can already be modified without involving ref / out just by using the standard Add / Remove methods already available on the type.

You are using a nonstandard form for event handlers. It is more conventional to stick to EventHandler<TEventArgs> where TEventArgs is some class deriving from EventArgs . Data to be passed back and forth from the event handler should be handled by using properties or methods on your custom EventArgs class.

Your event handler logic is not thread-safe. You need to capture a local copy of the event handler to account for the case when someone unsubscribes right after you do the null check. Here is the typical pattern:

// Capture the handler in a local
EventHandler<MyEventArgs> handler = this.MyEvent;
if (handler != null)
{
    // Invoke using the local copy
    handler(this, new MyEventArgs(/* ... */));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM