This question has already been answered:

Hello everyone, just recently started programming. I have a Signals list in which the signal is stored, inside each signal there must be a list of parameters and each parameter must have values, the values ​​are preferably also in the list.

At this stage, I'm trying to add parameters to an existing signal, but when I try to add, an error is caused:

System.NullReferenceException: "The object reference does not indicate an object instance."

How to fix it is not entirely clear.

class Program { static void Main(string[] args) { //Список с Сигналами List<Signal> Signals = new List<Signal>(); //Добавляем новый сигнал Signals.Add(new Signal() {VarName = "signal1"}); //Просматриваем все сигналы в Signals foreach (var signal in Signals) { //Добавляем в сигнал параметр Time и значение signal.parameters.Add(new Parameters() { paramName = "Time", value = 1}); foreach (var parameter in signal.parameters) { Console.WriteLine(parameter.paramName, ":", parameter.value); } } Console.Read(); } } public class Parameters { public string paramName { get; set; } public int value { get; set; } } public class Signal { public string VarName { get; set; } public List<Parameters> parameters; } 

Error in this line:

 signal.parameters.Add(new Parameters() { paramName = "Time", value = 1}); 

Marked as a duplicate by participants default locale , EvgeniyZ , freim , aleksandr barakin , 0xdb 11 Apr at 16:37 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • parameters not initialized, i.e. it contains null - gil9red

2 answers 2

Correct so:

  //Добавляем новый сигнал Signals = new List<Signal> { new Signal { VarName = "signal1", parameters = new List<Parameters>() } }; 
     public class Signal { public string VarName { get; set; } public List<Parameters> parameters = new List<Parameters>(); } 
    • why this crutch? why create something that will never be used (possibly) - pasha goroshko
    • @pashagoroshko you have a peculiar definition of a crutch. If the field is not used, then it makes no sense to create it, yes. In the sense of the whole field it makes no sense to determine if it is not used - tym32167
    • @pashagoroshko, and how is this usually implemented? - Ilya Chirkov
    • @ ChirkovIlya fields are usually initialized either in place, as I showed above, either in the constructor, or specified when creating an instance - tym32167
    • @ ChirkovIlya replied - pasha goroshko