Shall i always need to throw ArgumentNullException(well,extension methods in Enumerable throw ArgumentNullException) when an extension method is called on null?I would like to have a clarification on this?If the answer is an Yes and No please present both the cases.
+3
A:
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.
Adam Robinson
2010-06-07 18:19:52
+1
A:
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.
SWeko
2010-06-07 20:22:48