gorgabal
gorgabal

Reputation: 145

c# dictionary ObjectReference not set

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

Answers (1)

oerkelens
oerkelens

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

Related Questions