1

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?

Community
  • 1
  • 1
RandomProgrammer
  • 1,570
  • 1
  • 14
  • 23
  • Yep, the following works/crashes like a charm: Control c = null; c.DoStuff(). And in this case you want to have a nice exception. At least we do. ;-) It all depends I guess. – RandomProgrammer Nov 16 '09 at 20:05

2 Answers2

4

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 ;)

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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.

Maximilian Mayerl
  • 11,253
  • 2
  • 33
  • 40
  • Hi Maximilian, thank you for your swift answer. I prefer to stick with Microsoft way. And therefore prefer Jon's answer. – RandomProgrammer Nov 16 '09 at 13:33
  • I think I've heard that exceptions like `NullReferenceException` and `StackOverflowException` won't be throwable in .NET 4 anymore. – JulianR Nov 16 '09 at 13:47
  • @Julian: They are throwable. The thing that changes in .Net 4 is that, without a special attribute applied to the method, a method won't be able to catch Exceptions like StackOverflowException or OutOfMemoryException. – Maximilian Mayerl Nov 17 '09 at 10:31