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?

6
  • @Joe As an aside designs which rely on null values can be a potential maintenance issue, as every new use of members which can return null have to check for it. It is often desirable to have a design which avoids this. Commented Aug 3, 2010 at 21:21
  • 3
    That is an unusual arrangement, unless you have it set up as an out parameter (otherwise why even worry about receiving that parameter?). What are the side effects of setting it to null if it isn't? Commented Aug 3, 2010 at 21:21
  • 2
    Just out of curiosity could you tell us why you're mandating a null value? Commented Aug 3, 2010 at 21:21
  • I also want to know why you would ever want to do this? If you always want null, i.e., a known value, just don't take the parameter in the first place. Commented Aug 3, 2010 at 21:28
  • 4
    @Joe: So you basically want to throw an exception if there is an erroneous configuration and not if a value is null. I'd rather go for something like ConfigurationErrorException then or a custom exception expressing that fact. Commented Aug 3, 2010 at 21:52

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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.
3

I would probably use ArgumentOutOfRangeException

Comments

0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.