How to: Add Fields and Properties to a Class
You can use both fields and properties to store information in an object. Although fields and properties are almost indistinguishable from a client-application perspective, they are declared differently within a class. Whereas fields are simply public variables that a class exposes, properties use Property procedures to control how values are set or returned.
To add a field to a class
Declare a public variable in the class definition, as in the following code:
To add a property to a class
Declare a local variable within the class to store the property value. This step is necessary because properties do not allocate any storage on their own. To protect their values from direct modification, variables used to store property values should be declared as Private.
Preface property declarations with modifiers, such as Public and Shared, as appropriate. Use the Property keyword to declare the property name, and declare the data type that the property stores and returns.
Define Get and Set property procedures within the property definition. Get property procedures are used to return the value of a property and are roughly equivalent to functions in syntax. They accept no arguments and can be used to return the value of private local variables declared within the class used to store the property value. Set property procedures are used to set the value of a property; they have a parameter, usually called Value, with the same data type as the property itself. Whenever the value of the property is changed, Value is passed to the Set property procedure, where it can be validated and stored in a local variable.
Terminate Get and Set property procedures with End Get and End Set statements as appropriate.
Terminate the property block with an End Property statement.
If you are working within the Visual Studio integrated development environment (IDE), you can direct it to create empty Get and Set property procedures. Type Property PropName As DataType (where PropName is the name of your property, and DataType is a specific data type, such as Integer), and the property procedures appear in the Code Editor.
The following example declares a property in a class:
When you create an instance of ThisClass and set the value of the property One, the Set property procedure is called and the value is passed in the Value parameter, which is stored in a local variable named m_PropVal. When the value of this property is retrieved, the Get property procedure is called like a function and returns the value stored in the local variable m_PropVal.