Reputation: 145
Why does this code return a NullReferenceExeption
on the first if statement? How should it be remedied?
void Main()
{
addOrIncrement(new KeyValuePair<string,long>("1",1));
addOrIncrement(new KeyValuePair<string,long>("1",1));
}
public Dictionary<string, long> Result { get; set; }
public void addOrIncrement(KeyValuePair<string,long> pair){
if(Result.ContainsKey(pair.Key))
{
Result[pair.Key] += pair.Value;
} else {
Result.Add(pair.Key, pair.Value);
}
}
Upvotes: 0
Views: 89
Reputation: 5161
Result
is never initialised, so it's null
public Dictionary<string, long> Result { get; set; } = new Dictionary<string, long>();
Should do the trick
Upvotes: 2