About extension methods

Shall I always need to throw ArgumentNullException when an extension method is called on null? (Extension methods in Enumerable throw ArgumentNullException.) I would like to have clarification on this. If the answer is both "Yes" and "No" please present both the cases.

Upvotes: 0

Views: 103

Answers (2)

SWeko
SWeko

Reputation: 30872

I've seen this kinds of methods defined often as extension methods:

public static bool IsNull(this object item)
{
    return item == null;
}

and used like:

object o = null;
if (o.IsNull())
  return;

So, in this special case, it makes no sense to throw if the argument is null. Extension methods are not different from any other methods, just the syntax is fancier.

Upvotes: 2

Adam Robinson
Adam Robinson

Reputation: 185583

You need to throw it if the argument is null and you don't support that condition. If that isn't a problem, there's no need to throw the exception. One might expect in most cases that a null argument for the this argument would be an unsupportable condition, but by no means is that always the case.

The need for throwing this exception (and for null checking) is no different in extension methods than in traditional methods.

Upvotes: 5

Related Questions