john84 john84 - 1 year ago 96
C# Question

C# Nested typed lists

I've created a class witch contains a typed list and derives to another class that I created. This looks as follows:

namespace MyIntegretyCheck.Common
/// <summary>
/// Description of PolicyErrors.
/// </summary>
public partial class PolicyErrorEndingDates
public int ID_P {get;set;}
public DateTime DT_S_E {get;set;}
public DateTime DT_SC_E {get;set;}

public List<PolicyErrorDescr> Errors {get;set;}

public partial class PolicyErrorDescr
public string Field1{get;set;}
public string Field2 {get;set;}
public string F1IsThanF2 {get;set;}
public string Message {get;set;}
public int ErrorLevel {get;set;} //0= Info | 1= Warning | 2= Error


Now I created a typed list of
, added an entry and tried then to add entries of his nested list Errors as follows:

public List<PolicyErrorEndingDates> MyPolicyEndingDates()

DAL.PolicyEndingDates ped = new DAL.PolicyEndingDates();
List<PolicyErrorEndingDates> MyErrors = new List<PolicyErrorEndingDates>();

foreach(var m in ped.CheckTables())
bool HasError = false;
PolicyErrorEndingDates p = new PolicyErrorEndingDates();
p.ID_P = m.ID_P;

if(m.DT_S_E != m.DT_SC_E)
PolicyErrorDescr e = new PolicyErrorDescr();
HasError = true;
e.Field1 = "DT_S_E";
e.Field2 = "DT_SC_E";
e.Message = "blablabla...";
e.ErrorLevel = 3;


The Debugger crashed with the message
Object reference not set to an instance of an object
, at the line
inside my
. What did I do wrong? How can I create an instance of the nested list?

Answer Source

Did you assign a List<PolicyErrorDescr> instance to the Errors property?

First, I would probably make the Errors collection read-only from the outside, that is, the list can be changed, but you can't give it a new list.

This I would do by making the setter private:

public List<PolicyErrorDescr> Errors { get; private set; }

Then I would create a constructor and assign a collection instance to that property from it:

public PolicyErrorEndingDates()
    Errors = new List<PolicyErrorDescr>();

This should take care of the null reference exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download