开发者

Check input parameters on extension method [duplicate]

This question 开发者_StackOverflow社区already has answers here: Closed 11 years ago.

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:

  1. ArgumentNullException (as used below)
  2. InvalidOperationException
  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜