views:

46

answers:

2

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?

+4  A: 

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

Jon Skeet
A: 

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
Hi Maximilian, thank you for your swift answer. I prefer to stick with Microsoft way. And therefore prefer Jon's answer.
Florian
I think I've heard that exceptions like `NullReferenceException` and `StackOverflowException` won't be throwable in .NET 4 anymore.
JulianR
@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