0
foreach (KeyValuePair<uint, Character> kvp in World.AllChars)
{
    Character Charr = kvp.Value;
    Charr.Do(); <-- NullrefException: Charr is null
}

Code with the check:

foreach (KeyValuePair<uint, Character> kvp in World.AllChars)
{
    Character Charr = kvp.Value;
    if(Charr != null)
    {
       Charr.Do(); <-- NullrefException: Charr is null
    }
}

EDIT:

Nothing inside Do() causes it to be null, as it doesnt even get to execute Do() because Charr is null.

Thats how my loop looks like. I already tried to do a if != null check but it still goes past that and throws an nullref exception.

How can I prevent that? Im using a Concurrent Dictionary and a highly multithreaded server architecture.

Yuki
  • 25
  • 5

2 Answers2

1

The question mentions that you check for null but it's unclear on which value you are doing it. Consider the following code

Character Charr = kvp.Value;
if (Charr != null) { 
  Charr.Do();
}

It is not possible in this scenario for Char to be null. It's possible that a member of Charr is null and hence the Do method throws. If that is the case though it's likely that Character type is not suitable for multi-threaded scenarios (at least the way they are being used)

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

If you have a null check for Charr added and still get a null reference exception something in the Do() Method will cause this exception. Check the call stack of the exception or/and use a debugger to go through your code step by step.

Roland Bär
  • 1,720
  • 3
  • 22
  • 33
  • No, as I said, Charr itselfe is null. I checked it on debug (mouse over charr - shows null) – Yuki Jan 21 '14 at 14:49
  • I don't see a way how Charr can get null as it is a stack variable that is not influenced by other threads. But if you have it as a member variable it could of course be changed by other threads, and no concurrent list will take care of that. – Roland Bär Jan 21 '14 at 15:09