Search code examples
c#genericscollectionsienumerable

Adding to Collection when Collection is Null


I keep getting a null ref on the Children List when trying to add to the list via my property below

    public class Node<T> where T : INode
    {
        private readonly T _item;

        public IList<Node<T>> Children { get; set; } 

        public Node(T item)
        {
            _item = item;
            ParentNodeId = item.ParentNodeId;
        }


        public void AddChild(T childNode)
        {
            Children.Add(new Node<T>(childNode));
        }
....

And I wouldn't think you want to initiate the Children list every time it hits this property so what should I do to be able to add to this Node's children every time the calling code needs to populate it?


Solution

  • you can try something like this may be

        public void AddChild(T childNode)
        {
            if(this.Children == null)
            {
               this.Children = new List<Node<T>>();
            }
            this.Children.Add(new Node<T>(childNode));
        }