filipv
filipv

Reputation: 324

ArgumentNullException message without parameter name

I am throwing ArgumentNullException in part of my code in C#. I want to catch and display the error message of my exception. But without the parameter name. I want to pass the parameter name to the exception constructor.

throw new ArgumentNullException("myParameter", errorMessageStringVariable);

If I call error.Message I get something like

errorMessageStringVariable parameter name: myParameter

I want to display only the errorMessageStringVariable. Is it possible using ArgumentNullException, without some kind of formating on the error.Message?

Upvotes: 9

Views: 15513

Answers (2)

Ricardo Fontana
Ricardo Fontana

Reputation: 4813

If you call:

new ArgumentNullException(null, errorMessageStringVariable)

The exception message will be:

Value cannot be null. Parameter name: errorMessageStringVariable

If you instead use:

new ArgumentNullException(string.Empty, errorMessageStringVariable)

you will only get the error message.

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

If you want to construct the exception without the name, use:

new ArgumentNullException(null, errorMessageStringVariable)

But if you want to present an ArgumentNullException where the paramName is set, the answer seems to be no. You have to use string manipulation on the Message property.

You could create a new class that derives from ArgumentNullException.

Upvotes: 12

Related Questions