简体   繁体   中英

Dictionary.Add() returns NullReferenceException even though the added variables are not null

I have an object named Statistics with 3 parameters restartsPerBuildD , restartsByReleaseD and buildPerReleaseD which are of type Dictionary<string, double> .

I have a method which is supposed to get info for these variables and fill in these parameters, ultimately adding the object to a list. However, when I try to add them to the dictionary parameters, I am prompted with a NullReferenceException . The code is like below:

EDIT:

Also added the Statistics class in here:

public class Statistics
{
   public Dictionary<string, double> restartsPerBuildD { get; set; }
   public Dictionary<string, double> restartsByReleaseD { get; set; }
   public Dictionary<string, double> buildsPerReleaseD { get; set; }
}

And the functionality:

- On line:

statistics.restartsPerBuildD.Add(rbr.Key, _restartsPerBuild);

I get:

NullReferenceException

The error is nothing to do with the value you are adding, but comes from the fact that the Dictionary are you trying to add into is not yet initialised.

So in your statistics class although you have defined your properties because they are dictionaries then they must also be initialised.

So you should either create a default constructor or do this inline (see below).

public class Statistics
{
   public Dictionary<string, double> restartsPerBuildD { get; set; }  = new Dictionary<string, double>();
   public Dictionary<string, double> restartsByReleaseD { get; set; } = new Dictionary<string, double>();
   public Dictionary<string, double> buildsPerReleaseD { get; set; } = new Dictionary<string, double>();
}

Jason.kaisersmith is right, you haven't initialized the dictionary. Either you could do it that way, or simply initializing the dictionary in the constructor.

Option 1

public class Statistics
{
    Statistics()
    {
        restartsPerBuildD = new Dictionary<string, double>();
        restartsByReleaseD = new Dictionary<string, double>();
        buildsPerReleaseD = new Dictionary<string, double>();
    }
   public Dictionary<string, double> restartsPerBuildD { get; set; }
   public Dictionary<string, double> restartsByReleaseD { get; set; }
   public Dictionary<string, double> buildsPerReleaseD { get; set; }
}

Option 2

public class Statistics
{
   public Dictionary<string, double> restartsPerBuildD { get; set; }  = new Dictionary<string, double>();
   public Dictionary<string, double> restartsByReleaseD { get; set; } = new Dictionary<string, double>();
   public Dictionary<string, double> buildsPerReleaseD { get; set; } = new Dictionary<string, double>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM