Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting NullReferenceException in impossible situation (when checking for null)

I have a very simple check right at the beginning of one of my methods as follows:

public void MyMethod(MyClass thing)
{
    if(thing == null)
        throw new ArgumentNullException("thing");

    //Do other stufff....
}

But I'm getting stacktraces (from Elmah in a production environment) which appears to indicate that the "if(thing == null)" line is throwing a NullReferenceException. The first 2 lines of the stack trace are something like:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at MyLibrary.BL.AnotherClass.MyMethod(MyClass thing) in C:\Development\MyProject\trunk\MyLibrary.BL\AnotherClass.cs:line 100

MyClass is a fairly simple class with no operator overloads or anything like that, so I'm a bit stumped as to what is throwing the NullReferenceException!

Can anybody suggest scenarios that might cause this?

EDIT: I suspect "thing" might be null, but I really would expect an ArgumentNullException not a NullReferenceException - this is basically what this question is about. Is there maybe something that the framework or Elmah that is changing or mis-reporting the exception - or is the only explanation that the binaries are somehow out of date?

like image 364
mutex Avatar asked Oct 16 '12 00:10

mutex


3 Answers

It is impossible for if (thing == null) to throw a NullReferenceException.

This means that something else is going on. It's time to start using your imagination in conjunction with a firm resolve to ignore the possibility that the if caused a problem.

like image 171
John Saunders Avatar answered Oct 01 '22 22:10

John Saunders


The if statement can throw a NullReferenceException if MyClass defines the == operator incorrectly e.g.

class MyClass
{
   int A {get;set;}

   public static bool operator ==(MyClass a, MyClass b)
   {
      return a.A == b.A;
   }

   public static bool operator !=(MyClass a, MyClass b)
   {
      return !(a == b);
   } 
}
like image 28
Matthew Finlay Avatar answered Oct 02 '22 00:10

Matthew Finlay


Looks like the exception is coming from something up the chain that calls MyMethod. MyMethod() is throwing the Exception and nothing above is handling it, so whatever web framework you're in is throwing the HttpUnhandledException.

like image 21
speakingcode Avatar answered Oct 01 '22 22:10

speakingcode