Saturday, March 24, 2012

Object reference not set to an instance of an object - I hate these :)

Hi i hate these object reference not set to an instance of an object errors. Here's the code i have:

List<AnswersItem> answers = Answers.GetAnswers();
Hashtable newAnswers = new Hashtable();

foreach (Answer answer in answers)
{
if (newAnswers.ContainsKey(answer.QuestionID) && answer.Answer != newAnswers[answer.QuestionID].ToString())
{
// Log the answer
}

newAnswers[answer.QuestionID] = answer.Answer;
}

The problem

The line throwing the error is:

if (newAnswers.ContainsKey(answer.QuestionID) && answer.Answer != newAnswers[answer.QuestionID].ToString())

However i can't see what is wrong as i have set newAnswers to a new instance and i have checked if a key exists before using it but i still have an error. Appreciate if someone could help.

Thanks

answer.QuestionID or answer.Answer is null?


I think newAnswers Doesnt contains any think.

and also check for Answer veriable in loop.

Use debug , place breakpoint and used F10/F11 key , you definatly get solutions


Hi cheers it was answer.Answer returning null. I thought this property could not be null but some where it must have gone wrong. I have added a null check now.

Thanks for your help.

0 comments:

Post a Comment