0

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);
    }
}

1 Answer 1

2

Result is never initialised, so it's null

public Dictionary<string, long> Result { get; set; } = new Dictionary<string, long>();

Should do the trick

Sign up to request clarification or add additional context in comments.

1 Comment

wow, my head is not working today apparently. How did I miss that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.