C#: Best practice for validating “this” argument in extension methods

江枫思渺然 提交于 2019-11-30 20:48:32
JaredPar

You should throw an ArgumentNullException. You're attempting to do argument validation and hence should throw an exception tuned to argument validation. NullReferenceException is not an argument validation exception. It's a runtime error.

Don't forget, extension methods are just static methods under the hood and can be called as such. While it may seem on the surface to make sense to throw a NullReferenceException on an extension method, it does not make sense to do so for a static method. It's not possible to determine the calling convention in the method and thus ArgumentException is the better choice.

Also, you should not ever explicitly throw a NullReferenceException. This should only be thrown by the CLR. There are subtle differences that occur when explicitly throwing exceptions that are normally only thrown by the CLR.

This is also close to a dupe of the following

For consistency with the Enumerable LINQ operators, throw an ArgumentNullException (not a NullReferenceException).

I would do the validation in the TakeRandom method because the stack trace will then make it clear that it is TakeRandom which objects to being given a null argument.

Maybe I am crazy but since it is an argument, I would throw a ArgumentNullException :/

General rule of thumb though is to throw Exceptions that derive from System.ApplicationException when possible. NullReferenceException is something the framework/CLR would throw.

http://msdn.microsoft.com/en-us/library/system.exception(VS.71).aspx

Two categories of exceptions exist under the base class Exception:

The pre-defined common language runtime exception classes derived from SystemException. The user-defined application exception classes derived from ApplicationException.

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