-1

I have question about assigning value to the list<> member of another object. I'm receiving error saying that the list<> member is NULL reference. It seems that i have to instantiate the list<> member?

public class Person
{
   public string FirstName {set;get:}
   public string LastName {set;get;}
   public string Country {set;get;
   public List<string> Hobbies;

}

public class Survey
{
   public List<Person> Poll;

   public void StartPoll()
   {       
       Person p = new Person();
       p.FullName = "Billy";
       p.LastName = "Bob";
       p.Location = "America";
       p.Hobbies.Add("Hiker");// this is where error occurs
       p.Hobbies.Add("Musician");// this is where error occurs

       Poll = new List<Person>();
       Poll.Add(p);

   }

}
Phil
  • 339
  • 2
  • 13

1 Answers1

1

You need to instantiate Hobbies collection.

public class Survey
{

   public List<Person> Poll;
   public Person p;

   public void StartPoll()
   {
       p = new Person();
       p.FullName = "Billy";
       p.LastName = "Bob";
       p.Location = "America";
       p.Hobbies = new List<string>(); // This line is missing in your code.
       p.Hobbies.Add("Hiker");// this is where error occurs
       p.Hobbies.Add("Musician");// this is where error occurs

       Poll = new List<Person>();
       Poll.Add(p);

   }

}

Or modify your Person class as below:

public class Person
{
   public Person()
   {
        this.Hobbies = new List<string>(); // Since you are instantiating here, you don't need to instantiate again in Survey or wherever/whenever you instantiate Person object in your application.
   }
   public string FirstName {set;get:}
   public string LastName {set;get;}
   public string Country {set;get;
   public List<string> Hobbies; // Modify this to property public List<string> Hobbies {get; set;}

}
sam
  • 1,937
  • 1
  • 8
  • 14