Fixus
Fixus

Reputation: 4641

Why do I get this NullReferenceException?

I'm learning C# and having a problem with passing a reference.

double tmpNewEntry = -1;

for (int k = 0; k < pl2.Length; k++)
{
    p.countWithStepActivation(ref tmpNewEntry);
    // Console.WriteLine("answer = {0} | t = {1} | tmpNewEntry = {2}", p.answer, p.theta, tmpNewEntry);
    pl2[k].changeEntry(k, tmpNewEntry);
}

Now when I uncomment WriteLine() I get the proper result for tmpNewEntry but in the next line:

pl2[k].changeEntry(k, tmpNewEntry); 

I get a NullReferenceException. What am I missing?

Upvotes: 0

Views: 137

Answers (3)

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

You can do:

double tmpNewEntry = -1;

for (int k = 0; k < pl2.Length; k++)
{
     p.countWithStepActivation(ref tmpNewEntry);
     // Console.WriteLine("answer = {0} | t = {1} | tmpNewEntry = {2}", p.answer, p.theta, tmpNewEntry);
     if(pl2[k] != null)
     {
         pl2[k].changeEntry(k, tmpNewEntry);
     }
}

Upvotes: 0

MatrixManAtYrService
MatrixManAtYrService

Reputation: 9131

What is the value of pl2[k] before you get the error? I bet it's null.

My guess is that the .changeEntry reference doesn't make sense to c# because the object (pl2[k]) is null.

Upvotes: 1

parapura rajkumar
parapura rajkumar

Reputation: 24403

You problem is

pl2[k].changeEntry(....

Are you sure pl2[k] is not NULL be it an array or List element?

Upvotes: 2

Related Questions