views:

93

answers:

3

If I am expecting a null value and get a defined value (within a getter of a property) and want to throw an exception, what would be the proper way to do this in csharp? Is there anything defined already that makes sense in this situation?

+7  A: 

My guess would be:

throw new
    ArgumentException("Parameter was expected to be null, value was provided.");

ArgumentOutOfRangeException might also work, but is typically used when there is a well defined range rather than null vs. not null.

Justin Niessner
+1 Throwing your own exception gives you the ability to provide "human-readable" errors that make sense when the user sees them. Contextualizing errors is the best approach.
Achilles
+2  A: 

I would probably use ArgumentOutOfRangeException

AllenG
A: 

I've seen InvalidOperationException used, as in the context of trying to set something twice. For example,

if(displayMessage != null)
  throw new InvalidOperationException("The display message may not be set more than once.");

displayMessage = myAwesomeMessage;
Eric