ArgumentNullException or NullReferenceException from extension method?

若如初见. 提交于 2019-12-05 19:47:38
JaredPar

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.

Aside from all the other answers (which are good) I think it's worth looking at what Microsoft does for the sake of consistency... and the extension methods in Enumerable all throw ArgumentNullException as far as I can see.

Since extension methods can be used in C# 2.0, and they can be called just like static methods (you do not HAVE to use them as extension methods), you should use ArgumentNullException.

Just because they look like methods on the type doesn't mean that they are, or are always called like one.

ArgumentNullException. There is no requirement to call extension methods as though they were instance methods. You can call them as if they were normal methods. NullReferenceException would be completely incorrect in that case.

From the user's standpoint, the method looks and acts like an instance method, so if I were them, I would expect to see a NullReferenceException.

That said, I would suggest throwing either one or the other explicitly in the code, instead of just "happening" to throw one as in your first example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!