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?
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.
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.
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.
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"));
}
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.
Yes, it would be more clear to pass the name of property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With