ConcurrentDict doesnt prevent items to be null inside an loop

94 Views Asked by At
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.

2

There are 2 best solutions below

2
On BEST ANSWER

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.

2
On

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)