Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 720
core Avatar asked Apr 25 '09 04:04

core


2 Answers

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?
like image 107
JaredPar Avatar answered Oct 02 '22 16:10

JaredPar


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.

like image 20
itowlson Avatar answered Oct 02 '22 16:10

itowlson