FrankTan
FrankTan

Reputation: 1686

Initialiazation error cause by Out Parameter in C# function

I have the following code:

double dd;
Dictionary<string, double> dic = new Dictionary<string,double>();
bool notin = this.summedVars.TryGetValue(bacino, out dic);
if(notin == false)
    this.summedVars.Add(bacino,dic);
dic.TryGetValue(id, out dd);
dic[id] = dd + d;

When I run it I get the error:

dic is set to a null reference

How do I initialize summedVars with a new Dictionary without adding values?

Upvotes: 1

Views: 148

Answers (1)

Paul Fleming
Paul Fleming

Reputation: 24526

I suspect TryGetValue is nulling your output parameter (dic). You need a safety net after that line

e.g.

dic = dic ?? new Dictionary<string,double>();

Your code would become:

                double dd;
                Dictionary<string, double> dic;
                bool notin = this.summedVars.TryGetValue(bacino, out dic);
                dic = dic ?? new Dictionary<string,double>();
                if(notin == false)
                    this.summedVars.Add(bacino,dic);
                dic.TryGetValue(id, out dd);
                dic[id] = dd + d;

Upvotes: 2

Related Questions