Check input parameters on extension method [duplicate]
Possible Duplicate:
ArgumentNullException or NullReferenceException from extension method?
Which exception should be thrown here?
public static string DoStuff(this Control control)
{
if (control == null)
{
throw new ArgumentNullException();
}
// Code goes here...
}
I thought about the following:
- ArgumentNullException (as used below)
- InvalidOperationException
- NullReferenceException
My choice would be ArgumentNullException. Is this correct?
Yes, ArgumentNullException
is the right thing to do here IMO. It's still an argument, even if it can be used as an extension method.
In particular, this is what LINQ to Objects does, e.g. with the Select
method (and all the other Enumerable
extension methods). Follow Microsoft's lead, I say.
EDIT: I've just spotted this is a duplicate of this question, with an answer from Jared Parsons. Fortunately that answer agrees with mine ;)
I would throw a NullReferenceException, because this is what a normal instance method would throw. I want my extension methods to feel like normal instance methods.
精彩评论