This one will be very easy for you pros - but I've now wasted hours on it myself. Here's a simplified version of what I'm trying to do:
(1) I have an 'Employment' class which can store 3 strings [EmployerName], [JobTitle] and [PeriodOfEmployment]. I am successfully able to create an instance of Employment and populate it with example entries.
(2) I want to populate a wrapper class called 'CurriculumVitae' which contains a [PersonName] string plus a List variable containing all Employments ever held by the person. I want to use a loop to add instances of Employment to the instance of CurriculumVitae, so that the CurriculumVitae class ends up holding a person's full job history in its EmploymentsList.
(3) In Visual Studio am getting the error message:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
CurriculumVitae.EmploymentsList.get returned null.'.
My simplified code is:
using System;
using System.Collections.Generic;
namespace CurriculumVitaeExample
{
class Program
{
static void Main(string[] args)
{
var CurriculumVitae = new CurriculumVitae();
CurriculumVitae.Open();
}
}
}
My Employment class looks like this:
public class Employment
{
public string EmployerName { get; set; }
public string JobTitle { get; set; }
public string PeriodOfEmployment { get; set; }
}
My CurriculumVitae class tries to make use of the Employment class in a List, like this:
public class CurriculumVitae //(version 1)
{
public string PersonName { get; set; }
public List<Employment> EmploymentsList { get; set; }
// Open method:
public void Open()
{
Employment Employment = new Employment();
Employment.EmployerName = "McDonalds";
Employment.JobTitle = "Ice Cream Guru";
Employment.PeriodOfEmployment = "Jan 2019 - Present";
this.EmploymentsList.Add(Employment);
}
}
I also tried adding a constructor for the EmploymentsList within the CurriculumVitae class but it didn't help:
public class CurriculumVitae //(version 2)
{
// Constructor:
public CurriculumVitae()
{
List<Employment> EmploymentsList = new List<Employment>();
}
...
}