Darrell Norton's Blog [MVP]

Sponsors

The Lounge

Wicked Cool Jobs

News

  • Darrell Norton pic

    MVP logo

    View Darrell Norton's profile on LinkedIn

    Currently Reading:

    weewar.com

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Argument Exception utility

Nils Jonsson has posted a code sample on The Code Project that makes it easy to raise argument exceptions. You know, argument exceptions are those exceptions you are supposed to raise when the parameters passed in to your method don’t match what you thought they would be? Nils makes it easy by including the following 9 base methods (plus overloads):

  • ThrowIfArgumentDifferentType() throws ArgumentException if an argument is not an instance of a given type.
  • ThrowIfArgumentIncompatibleType() throws ArgumentException if an argument cannot be cast to a given type.
  • ThrowIfArgumentInvalidEnumValue() throws InvalidEnumArgumentException if an argument is not a constant in a given enumerated type.
  • ThrowIfArgumentNull() throws ArgumentNullException if an argument is a null reference (Nothing in Visual Basic).
  • ThrowIfArgumentOutOfRange() throws ArgumentOutOfRangeException if an argument is less than a given minimum or greater than a given maximum.
  • ThrowIfArgumentOutOfRangeExclusive() throws ArgumentOutOfRangeException if an argument is less than or equal to a given lower bound or greater than or equal to a given upper bound.
  • ThrowIfArgumentOutOfRangeIncludeMax() throws ArgumentOutOfRangeException if an argument is less than or equal to a given lower bound or greater than a given maximum.
  • ThrowIfArgumentOutOfRangeIncludeMin() throws ArgumentOutOfRangeException if an argument is less than a given minimum or greater than or equal to a given upper bound.
  • ThrowIfArrayArgumentDifferentRank() throws RankException if an array argument does not have a given number of dimensions.

With these methods, it takes a single line of code to check a parameter and throw the appropriate exception. I’ve been writing methods similar to this in an ad-hoc manner for a while, but now I can take advantage of someone else’s hard work. In true TDD spirit, Nils also includes 620 NUnit test cases developed with the fabulous TestDriven.NET add-in by Jamie Cansdale!


Posted Mon, Dec 13 2004 6:43 AM by Darrell Norton

[Advertisement]

Comments

Jonathan de Halleux wrote re: Argument Exception utility
on Tue, Dec 14 2004 3:37 AM
I still believe the C# compiler should be able to do this kind of things. Nice to see that there are still quality articles on CodeProject.
Darrell wrote re: Argument Exception utility
on Tue, Dec 14 2004 5:52 AM
Jonathan - I agree that the compiler should check for us. But in the meantime I'll happily reduce my effort as much as possible.
Devlicio.us