Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What parameter name to use for ArgumentException in property setters

From MSDN:

Every ArgumentException should carry the name of the parameter that causes this exception.

My question: if a property setter should throw an ArgumentException, should I give it the setter's parameter name (default: value) or the name of the property?

Example:

    Private _myProperty As String
    Public Property MyProperty As String
        Get
            Return _myProperty
        End Get
        Set(value As String)
            If String.IsNullOrEmpty(value) Then
                ' what I've been doing for the last 2 years
                Throw New ArgumentNullException("value", "value cannot be empty")

                ' what I think I should be doing instead
                Throw New ArgumentNullException("MyProperty", "value cannot be empty")
            End If
            _myProperty = value
        End Set
    End Property

I hope that made sense. What do you think?

Edit

I guess another solution would be to rename value to something more meaningful, then use that as the value for paramName. But somehow that doesn't seem like it's the right thing to do.

like image 208
Steven Liekens Avatar asked Jan 29 '26 23:01

Steven Liekens


1 Answers

According to an example from Catching and Throwing Standard Exception Types on MSDN you should keep setting "value" as a parameter name:

Do use value for the name of the implicit value parameter of property setters.

So that's ok:

Throw New ArgumentNullException("value", "value cannot be empty")
like image 69
MarcinJuraszek Avatar answered Feb 01 '26 14:02

MarcinJuraszek