Null reference makes no sense

  • Thread starter Thread starter Marshall Belew
  • Start date Start date
M

Marshall Belew

My stack trace contains:
System.NullReferenceException: Object reference not set to an instance
of an object.

but the line of code it refers to looks like this:


if (null == unit || ! unit.Enabled)
return;


Am I just missing something? The short-circuit evaluation of this
line should never allow the "! unit.Enabled" to be tested if "null ==
unit".

I've seen this fairly randomly. I can't reproduce it every time. I'm
willing to bet that it's a memory corruption somewhere.

Any tips on debugging this weirdness?

Marshall Belew
 
Marshall Belew said:
My stack trace contains:
System.NullReferenceException: Object reference not set to an instance
of an object.

but the line of code it refers to looks like this:

if (null == unit || ! unit.Enabled)
return;

Am I just missing something? The short-circuit evaluation of this
line should never allow the "! unit.Enabled" to be tested if "null ==
unit".

I've seen this fairly randomly. I can't reproduce it every time. I'm
willing to bet that it's a memory corruption somewhere.

Hmm... I wouldn't make any bets just yet.
Any tips on debugging this weirdness?

Well, what is "unit" in this case? If it overloads the == operator,
that could be the problem. Are you *absolutely* sure it's actually
occurring on this line, rather than near it? Could you post some more
code?


By the way, I'd suggest writing tests in the more natural way of

if (unit==null || !unit.Enabled)

by the way - I suspect I'm not alone in finding this considerably
easier to use. The problem of accidental assignment is gone in C#
(unless you compare booleans with true and false directly) as it's
stricter about what the type of expression of the "if" statement can
be.
 
Are you using multiple threads? If some other thread would set unit to null
right after the "null == unit" test but before the "! unit.Enabled" request,
that line would throw an exception (but not every time).
Is it possible the "Enabled" is actually a property, and that the exception
is thrown inside the "get" function?
What is "unit" anyway? Is it a local/member/instance variable? A property?

Debugging tips:
1. Don't panic
2. Let the debugger break on exceptions, and see if "unit" is null when that
exception is fired. Maybe make a local copy of the variable before the
assignment (or somewhere else) to see if multithread- or memory corruption
issues could explain the behaviour.
3. Split the if in two lines (one if for the null-check, one for the
'enabled' check), to see for sure which one crashes.
4. Finally (if everything else fails) remove every piece of code from your
app until the error disappears...

Niki
 
Back
Top