Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top