0

I do you set and get a list of type class program property in Main ? if I do I get an Exception?

public class Person 
{
    public List<Person> Children { get; set; }
    public string Names { get; set; }
}

static void Main(string[] args) 
{
    var person = new Person 
    {
        Names = "King"
    };
    
    person.Children.Add(new Person()); // Null Reference Exception
}
atiyar
  • 7,762
  • 6
  • 34
  • 75
  • 1
    You can't use `Children` when it is null. Create an instance of it first like in the answer below that does not give you an explanation of why. – Crowcoder Feb 21 '21 at 17:32

1 Answers1

2

Try this:

   var person = new Person{Names= "King" , Children=new List<Person>()};
   person.Children.Add(new Person())  
Serge
  • 40,935
  • 4
  • 18
  • 45