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

最后都变了- 提交于 2019-11-30 04:55:26

问题


Let's say I have an extension method

public static T TakeRandom<T>(this IEnumerable<T> e)
{
    ...

To validate the argument e, should I:

A) if (e == null) throw new NullReferenceException()
B) if (e == null) throw new ArgumentNullException("e")
C) Not check e

What's the consensus?

My first thought is to always validate arguments, so thrown an ArgumentNullException. Then again, since TakeRandom() becomes a method of e, perhaps it should be a NullReferenceException. But if it's a NullReferenceException, if I try to use a member of e inside TakeRandom(), NullReferenceException will be thrown anyway.

Maybe I should peak using Reflector and find out what the framework does.


回答1:


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

  • ArgumentNullException or NullReferenceException from extension method?



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/788218/c-best-practice-for-validating-this-argument-in-extension-methods

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