Let's say we have the below data structure

public class Lead
{
public string LeadFirstName { get; set; }
public List<Document> Documents { get; set; }
}
public class Document
{
public int DocumentId { get; set; }
public string DocumentPath { get; set; }
}

When we are doing the below stuff

Lead lead = new Lead();
lead.LeadFirstName = "Test";
lead.Documents.Add(new Document{ DocumentId = 1, DocumentPath = @"C:\test\abc.doc"});

we are encountering Null Reference exception. What is the root cause of that and how to solve it?

 Posted by Rajnilari2015 on 6/23/2016 | Category: C# Interview questions | Views: 490 | Points: 40
Answer:

The reason is we are not instantiating the list of documents.We need to initialize the collection. Below is the way to initialize the the collection inside the constructor and to get the program work

public class Lead

{
public Lead()
{
Documents = new List<Document>();
}

public string LeadFirstName { get; set; }
public List<Document> Documents { get; private set; }
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response