Set Statement - Visual Basic (original) (raw)

Declares a Set property procedure used to assign a value to a property.

Syntax

[ <attributelist> ] [ accessmodifier ] Set [([ByVal value [ As datatype ]])]  
    [ statements ]  
End Set  

Parts

attributelist
Optional. See Attribute List.

accessmodifier
Optional on at most one of the Get and Set statements in this property. Can be one of the following:

See Access levels in Visual Basic.

value
Optional. Parameter containing the new value for the property. If not given (that is if parameter list is not present or is empty), an implicit parameter named value is defined. The data type of this implicit parameter is the data type of the property where this Set statement is declared.

datatype
Required if value is present and Option Strict is On. Cannot be present if value is not given. Data type of the value parameter. The data type specified must be the same as the data type of the property where this Set statement is declared.

statements
Optional. One or more statements that run when the Set property procedure is called.

End Set
Required. Terminates the definition of the Set property procedure.

Every property must have a Set property procedure unless the property is marked ReadOnly. The Set procedure is used to set the value of the property.

Visual Basic automatically calls a property's Set procedure when an assignment statement provides a value to be stored in the property.

Visual Basic passes a parameter to the Set procedure during property assignments. If you do not supply a parameter for Set, the integrated development environment (IDE) uses an implicit parameter named value. The parameter holds the value to be assigned to the property. You typically store this value in a private local variable and return it whenever the Get procedure is called.

The body of the property declaration can contain only the property's Get and Set procedures between the Property Statement and the End Property statement. It cannot store anything other than those procedures. In particular, it cannot store the property's current value. You must store this value outside the property, because if you store it inside either of the property procedures, the other property procedure cannot access it. The usual approach is to store the value in a Private variable declared at the same level as the property. You must define a Set procedure inside the property to which it applies.

The Set procedure defaults to the access level of its containing property unless you use accessmodifier in the Set statement.

Rules

Behavior

Example

The following example uses the Set statement to set the value of a property.

Class propClass
    Private propVal As Integer
    Property Prop1() As Integer
        Get
            Return propVal
        End Get
        Set(ByVal value As Integer)
            propVal = value
        End Set
    End Property
End Class

See also