ArgumentNullException or NullReferenceException from extension method?

In general, exceptions included, you should treat an extension method as if it were a normal static method. In this case you should throw an ArgumentNullException.

Throwing a NullReferenceException here is a bad idea for a few reasons

  • A null reference did not actually occur so seeing one is counterintuitive
  • Throwing a NullReferenceException and causing a NullReferenceException to occur produce discernably different exceptions (One way to see the difference is the error code). This is true of many exceptions that are thrown by the CLR.

See When can you catch a StackOverflowException (a post I did on this subject).

  • It’s perfectly legal to call an extension method just as if it were a regular method. In that case I would certainly not except a NullReferenceException, but instead an ArgumentNullException.

Leave a Comment