Wednesday, February 03, 2010

ArgumentException vs ArgumentNullException

Ok, maybe I’m missing the point, but here is an item I don’t understand: When you want to throw an ArgumentException with the parameter name and a message as arguments, then the parameter name is the first parameter. When you use ArgumentNullException it’s just the other way round. Sounds complicated? It becomes more apparent once we look at some source code:

    1 public void DoSomething(string paramName) {

    2    if (paramName == null) {

    3       throw new ArgumentNullException(

    4          "paramName", // Must be first parameter here

    5          "Parameter cannot be null."

    6       );

    7    }

    8    if (paramName.Length < 10) {

    9       throw new ArgumentException(

   10          "String must have at least 10 characters.",

   11          "paramName"  // Must be second parameter here

   12       );

   13    }

   14    // ... rest of the method ...

   15 }

I haven’t noticed this in the past but nevertheless: Unless I’m totally overlooking the brilliant idea behind this, I’m not quite sure whether this inconsistency makes using these classes easier…

It’s certainly not a big issue and it’s probably too late anyways to fix this particular problem. I still wanted to rant a bit… and I’ll take this as an opportunity to search for similar inconsistencies in my own code.


I just noticed: This is my 100th post on this blog! Time to celebrate. Cheers!

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!