Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value to assign to 'paramName' parameter for ArgumentException in C# property setter?

If an invalid value is passed to a property setter and an ArgumentException (or possibility a class derived from it) is thrown, what value should be assigned to the paramName parameter?

value, since it seemingly is the actual argument?

Wouldn't it be more clear to pass the name of the property instead?

like image 970
mafu Avatar asked Mar 25 '09 12:03

mafu


People also ask

When should you throw an ArgumentException?

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. The ParamName property identifies the invalid argument.

How do you handle an argument out of range exception in C#?

If the string is empty, as the final string passed to the method is, the method throws an ArgumentOutOfRangeException exception. You can eliminate the exception by testing whether the string's String. Length is greater than zero or by calling the IsNullOrEmpty method to ensure that the string is not null or empty.

What is InvalidOperationException in C#?

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call. For example, an InvalidOperationException exception is thrown by methods such as: IEnumerator.


3 Answers

After extensive poking around with Reflector (trying to find a CLR object with a writable Property), the first one I found (FileStream.Position) using "value" as the argument name:

if (value < 0L)
{
    throw new ArgumentOutOfRangeException("value", 
                 Environment.GetResourceString("NeedNonNegNum"));
}
like image 154
James Curran Avatar answered Oct 13 '22 00:10

James Curran


ArgumentExceptions contain the name of the parameter which is not valid. For a property setter the actual parameter is named value (in both source and generated code). It's more consistent to use this name.

like image 22
JaredPar Avatar answered Oct 13 '22 00:10

JaredPar


Yes, it would be more clear to pass the name of property.

like image 29
alex Avatar answered Oct 12 '22 23:10

alex