What to chose ArgumentNullException or NullReferenceException

I'm writing a small lib of method extensions.

For example we have extension method

public static T GetRandom<T>(this IEnumerable<T> collection)

Which exception ArgumentNullException or NullReferenceException will be the clearest for case when collection is null? Or something else?

Jon Skeet
people
quotationmark

It's the argument which is null, so you should throw an ArgumentNullException. You should basically never throw NullReferenceException directly - it should only get thrown (automatically) when you try to dereference a null value.

The fact that you're writing an extension method doesn't change the fact that really it's a static method and collection is a parameter.

As usual, specify the name of the parameter which is null, using nameof if you're using C# 6:

public static T GetRandom<T>(this IEnumerable<T> collection)
{
    if (collection == null)
    {
        throw new ArgumentNullException(nameof(collection));
    }
    ...
}

(As an aside, check out MoreLINQ, which may well have most of your methods already...)

people

See more on this question at Stackoverflow