user6493962
user6493962

Reputation:

C# passing Object from List<T> as parameter

I have a List where i store some values. I defined an event which should pop up and return the last Object from that List to its EventArgs-Class-Constructor.

But when the Event gets fired, i get a System.NullException at this line:

OnID(this, new OnIDEventArgs(ID_List.Last()));

Im trying to pass the last IDs-Object to the OnIDEventArgs-Constructor. Why is this a NullException?

public delegate void EventHandler(object sender, OnIDEventArgs e);
public event EventHandler OnID;

IDs result = ID_List.FirstOrDefault(x => x.TID == tid_value);


    if (result != null)
       { //stuff }
    else {
       ID_List.Add(new IDs
                    {
                        TID = tid_value,
                        CENTID = centid_value,
                        IDCount = 1
                    });
       OnID(this, new OnIDEventArgs(ID_List.Last())); //System.NullException comes up here
    }

IDs class

public class IDs
{
    public string TID { get; internal set; }
    public string CENTID { get; internal set; }
    public int IDCount { get; internal set; }
}

EventArgs Class

public class OnIDEventArgs : EventArgs
    {
        public string LastTID { get; private set; }
        public string LastCENTID { get; private set; }
        public int IDCount { get; private set; }
        public OnIDEventArgs(IDs result)
        {
            this.LastTID = result.TID;
            this.LastCENTID = result.CENTID;
            this.IDCount = result.IDCount;

        }
    }

Upvotes: 0

Views: 169

Answers (1)

Sweeper
Sweeper

Reputation: 270890

This is probably due to that nothing subscribed to the OnID event, so the OnID delegate is null and thus calling Invoke on it will throw an NRE.

To avoid this, simply check whether OnID is null first:

if (OnID != null) {
    OnID(this, new OnIDEventArgs(ID_List.Last()))
}

Or:

OnID?.Invoke(this, new OnIDEventArgs(ID_List.Last())

Upvotes: 1

Related Questions