Search code examples
c#exceptionargumentexceptionargumentnullexception

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?


Solution

  • 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.