Getting an error: Object reference not set to an instance of an object
This is my C# code.
public class Person
{
public List<Employee> empDetails;
}
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string proj { get; set; }
public string No { get; set; }
}
//This method is defined in a service
public void ReadFiles()
{
DirectoryInfo dir = new DirectoryInfo("E:/NewFolder/NewFiles");
FileInfo[] files = dir.GetFiles("*.*");
Person p = 开发者_StackOverflow中文版new Person();
Employee e = new Employee();
foreach (FileInfo f in files)
{
XmlDocument doc = new XmlDocument();
doc.Load(f.FullName);
e.empId = doc.GetElementsByTagName("Id")[0].InnerText;
e.empName = doc.GetElementsByTagName("Name")[0].InnerText;
e.empSeatNo = doc.GetElementsByTagName("No")[0].InnerText;
e.projGroup = doc.GetElementsByTagName("Grp")[0].InnerText;
p.empDetails.Add(e); //Here I get the error "Object reference not set to an instance of an object"
}
}
Any helps appreciated.
The Person class does not initialise empDetails
. Most people will do this in the constructor.
public class Person
{
public Person()
{
empDetails = new List<Employee>();
}
public List<Employee> empDetails { get; private set; }
}
Also your case for the property names does not follow convention. Normaly it would EmpDetails or even better EmployeeDetails.
The list is never assigned; this should work:
public class Person
{
private readonly List<Employee> empDetails = new List<Employee>();
public List<Employee> EmploymentDetails { get { return empDetails; } }
}
(and access .EmploymentDetails
, i.e. p.EmploymentDetails.Add(e);
)
精彩评论