0

I have the following three classes defined.

public class FrequencyRecord
{
    public double Frequency;
    public int Duration;
}

public class EntryRecord
{
    public string Name;
    public Boolean Status;
    public long TotalTime;
    public FrequencyRecord[] FreqTime = new FrequencyRecord[25];
    public string Description;
}

public class Salv7Profile
{
    public string Version;
    public string SoftVersion;
    public string Name;
    public DateTime CreateDate;
    public DateTime LastModDate;
    public int Count;
    public EntryRecord[] Entries = new EntryRecord[99];
    public int Type;                         
}

Then I create an instance:

public static Salv7Profile IntProfile = new Salv7Profile();

Assigning a value to:

IntProfile.Name = "Peter"; 

works fine, But if I try:

IntProfile.Entries[1].Name = "Peter"; 

It throws an error: [System.NullReferenceException] "Object reference not set to an instance of an object."}

Being a novice at C#, how do I access the nested Entries class?

vidriduch
  • 4,753
  • 8
  • 41
  • 63

1 Answers1

5

The problem is that you've created an array, but that array is just full of null references to start with. You'd need something like:

EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries[1] = record;

to replace the array element with a reference to the newly-created EntryRecord.

It would almost certainly be better if you changed Entries to be a List<EntryRecord> though, and just used:

EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries.Add(record);

or more briefly, using an object initialzier:

IntProfile.Entries.Add(new EntryRecord { Name = "Peter" });

I would also strongly recommend against having public fields; use properties instead, and consider making your types immutable if you can.

(I'd encourage to think about whether you really need the IntProfile field to be static, too... static fields imply global state, which is harder to test and reason about.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194