Home > Articles > Programming > Visual Basic

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Defining Properties

The properties of a class define the data associated with the class. For example, a Product class has ProductName, ProductID, and InventoryDate properties. Each object created from the class can have a different set of values for these properties.

This section details the process of creating a property. It then covers some additional techniques for working with properties.

Creating the Property

Create a property in a class for each data attribute identified for the class during the design phase. Following best practices, defining properties requires two steps.

First you create a private variable to retain the property value. This private variable is called a backing variable or backing field and retains the property's value. You make the variable private so that it cannot be directly accessed by any code outside of the class.

Next you create a Property statement. The Property statement defines the property and the accessors used to get and set the property. The Set accessor, sometimes called the setter, sets the property's value, and the Get accessor, sometimes called the getter, returns the property's value.

This technique encapsulates the property by providing access to it only through the accessors. You can write code in the accessors to validate data, perform formatting, or any other business logic.

To define a property:

  1. Open the class in the Code Editor.
  2. Declare a private variable for the property.

    For example:

    Private _ProductName As String
    

    By making the variable private, you ensure that code outside of this class can not access the property directly. All code must access the variable value through the Property statement.

    Use good naming conventions for your private variable. There are several common conventions, such as prefixing the property name with m or m_ to define the variable as member-level. The convention that is currently gaining popularity is to prefix the property name with an underscore to indicate that the variable should not be used anywhere in the code except in the Property statement.

  3. Create the Property statement for the property.

    For example:

    Public Property ProductName() As String
    

    Use good naming conventions for your property name. The recommended convention is to use the property's human-readable name, concatenating the words and using Pascal case, whereby each word in the name is capitalized.

  4. Press the Enter key to automatically generate the remaining structure of the Property statement:
    Public Property ProductName() As String
        Get
    
        End Get
        Set(ByVal value As String)
    
        End Set
    End Property
    
  5. Add code within the Get and Set blocks.

The minimum code in the getter returns the value of the private variable:

Get
    Return _ProductName
End Get

Add any other code to the getter, such as formatting or data conversions. For example, for a product number, the getter could add hyphens or other characters used by the human reader that are not necessarily stored with the actual data.

The minimum code in the setter sets the value of the private variable:

Set(ByVal value As String)
    _ProductName = value
End Set

Add any other code to the setter, such as validation or data conversion. For example, code could validate that the product name is not empty before it is assigned to its private variable.

Repeat these steps to define each property of your class. Alternatively, you can use code snippets or the Class Designer, as described in the next chapter, to assist you in defining the properties of your class.

Use properties to define the data managed by your business object. Use Property statements to provide access to the properties from other parts of the application.

Property Statements Versus Public Variables

The example in the preceding section seemed like much more code than simply adding a public variable. Why bother with Property statements?

Using a private variable and public Property statements has several advantages over just using public variables:

  • You can add code that is executed before a property is assigned. This code can perform validation, such as to ensure that no invalid values are assigned to the property.
  • You can add code that is executed before a property is retrieved. This code can format or convert the value. For example, it could add dashes to the product number for the human reader even though the dashes are not stored with the data.
  • Without a Property statement, any code that references the class can manipulate or destroy the property value at will.
  • Some of the Visual Studio tools, such as object binding, recognize only properties defined with Property statements. (See Chapter 7, "Binding the User Interface to the Business Objects," for more information on object binding.)

For these reasons, always use private variables and public Property statements to define the properties for your classes.

Documenting the Property

It is always a good idea to add documentation for a property immediately after defining the property. By adding the documentation right away, you have it in place so that you can use the documentation as you build the remainder of the application.

To document the property:

  1. Open the class in the Code Editor.
  2. Move the insertion point immediately before the word Public in the Public Property statement.
  3. Type three comment markers, defined in Visual Basic as apostrophes ('''), and press the Enter key.

    The XML comments feature automatically creates the structure of your property documentation as follows:

    ''' <summary>
    '''
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    
  4. Type a summary of the property between the summary tags, the value of the property between the value tags, and so on. Your documentation may be similar to this:
    ''' <summary>
    ''' Gets or sets the product name
    ''' </summary>
    ''' <value>Product Name</value>
    ''' <returns>Product Name</returns>
    ''' <remarks></remarks>
    

Use the summary tags to describe the purpose of the Property statement. By convention, a Property statement summary begins with the text "Gets or sets the..." for a read-and-write property, "Gets the..." for read-only properties, and "Sets the..." for write-only properties.

In this example, the value and returns tags don't provide very useful information, because the product name is self-explanatory. These two tags could be deleted in this case. However, in other cases the property may not be as obvious, so the documentation defined in the XML tags is more useful. For example, a Status property is not as obvious, and the XML documentation could provide further information, such as what the status value means and what it actually returns.

When you provide a summary of a property using XML comments, the summary appears in appropriate places within Visual Studio. For example, the summary appears in the Intellisense List Members box when you type the object variable name and a period (.).

Using XML comments to document your properties makes it easier for you and other developers to work with your properties.

Defining Property Accessibility

In most cases, properties are public. The primary purpose of properties is to provide public access to the data relating to a particular object. But in some cases, you may want the property to be read-only and, in rare cases, write-only. You can define a property's accessibility using additional keywords in the Property statement.

Some fields should be changed only by code in the class, not by any code outside the class. For example, a ProductID should not be changed by code outside the class, because the ID is the key property used to identify the product. It should be set only when the product is created and then never changed. (See Chapter 8 for more information on primary key fields.)

You can define a property to be read-only using the ReadOnly keyword. If you need to define a property as write-only, you can use the WriteOnly keyword.

Public ReadOnly Property ProductID() As Integer
    Get

    End Get
End Property

When you make the property read-only or write-only using the keyword, the code in the class cannot access the property either. If the property is read-only, the code in the class must access the private backing variable to update the value. It would be better to define the accessibility on the accessors so that the getter could be public but the setter could be private. This would allow the code in the class to set the property but make it appear read-only outside this class.

To define separate accessibility on the accessors, add an accessibility keyword to either the getter or setter:

Public Property ProductID() As Integer
    Get

    End Get
    Private Set(ByVal value As Integer)

    End Set
End Property

Notice the Private keyword on the setter. This allows the getter to be public but restricts the setter to be private. The code within the class can then get or set the property, and code outside the class can only get the property.

Some restrictions and rules apply when you use accessibility on the accessors:

  • The accessibility on the Property statement must be less restrictive than the accessibility on the accessor.

    For example, you cannot define the Property statement to be private and then make the getter public.

  • You can add accessibility to the getter or setter, but not both.

    If the getter needs to be friend and the setter needs to be private, for example, make the Property statement friend (the least restrictive), and make the setter private.

  • If you use the ReadOnly or WriteOnly keywords, you cannot add accessibility on the accessor.

Define accessibility appropriately to ensure that your properties are accessed only as they should be. Most properties are public, but for some properties, such as IDs, define private setters to allow reading but not setting of the property.

Handling Nulls

A data type is said to be nullable if it can be assigned a value or a null reference. Reference types, such as strings and class types, are nullable; they can be set to a null reference, and the result is a null value. Value types, such as integers, Booleans, and dates, are not nullable. If you set a value type to a null reference, the result is a default value, such as 0 or false. A value type can express only the values appropriate to its type; there is no easy way for a value type to understand that it is null.

The .NET Framework 2.0 introduces a Nullable class and an associated Nullable structure. The Nullable structure includes the value type itself and a field identifying whether the value is null. A variable of a Nullable type can represent all the values of the underlying type, plus an additional null value. The Nullable structure supports only value types because reference types are nullable by design.

For example, say you have a Product class with a ProductID property defined as an integer, a ProductName property defined as a string, and an InventoryDate property defined as a date. The following code sets each property to Nothing to assign a null reference:

Dim prod as Product
prod = New Product
prod.ProductID = Nothing
prod.ProductName = Nothing
prod.InventoryDate = Nothing

Debug.WriteLine(prod.ProductID)   ' Displays 0
Debug.WriteLine(prod.ProductName) ' Displays (Nothing)
Debug.WriteLine(prod.InventoryDate)
                                  ' Displays 1/1/0001 12:00:00 AM

If you view these values, they are 0, Nothing, and 1/1/0001 12:00:00 AM, respectively. The ProductID and InventoryDate properties are value types and therefore cannot store a null. Instead, they store a default value when they are assigned a null reference.

There may be cases, however, when you need your code to really handle a null as a null and not as a default value. It would be odd, for example, to handle a null date by hard-coding a check for the 1/1/0001 date.

To make a value type property nullable, you need to declare it using the Nullable structure. However, you still want your property to be strongly typed as an integer, date, Boolean, or the appropriate underlying type. The ability to use a class or structure for only a specific type of data is the purpose of generics.

Generics allow you to tailor a class, structure, method, or interface to a specific data type. So you can create a class, structure, method, or interface with generalized code. When you use it, you define that it can work only on a particular data type. This gives you greater code reusability and type safety.

The .NET Framework built-in Nullable structure is generic. When you use the structure, you define the particular data type to use.

As a specific example, an InventoryDate property that allows the date to be a date or a null value uses the generic Nullable structure as follows:

Private _InventoryDate As Nullable(Of Date)
Public Property InventoryDate() As Nullable(Of Date)
    Get
        Return _InventoryDate
    End Get
    Set(ByVal value As Nullable(Of Date))
        _InventoryDate = value
    End Set
End Property

Notice the syntax of the Nullable structure. Since it supports generics, it has the standard (Of T) syntax, where T is the specific data type you want it to accept. In this case, the Nullable structure supports dates, so the (Of Date) syntax is used. This ensures that the Nullable structure contains only a date or a null value.

You can then use this property in your application as needed. For example:

Dim prod as Product
prod = New Product
If prod.InventoryDate.HasValue Then
    If prod.InventoryDate.Value < Now.Date.AddDays(-10) Then
        MessageBox.Show("Need to do an inventory")
    End If
Else
    MessageBox.Show("Need to do an inventory - never been done")
End If

The HasValue property of the Nullable class defines whether the value type has a value—in other words, whether it is null. If it does have a value, you can retrieve the value using the Value property of the Nullable class.

The Nullable structure is exceptionally useful when you're working with databases, because empty fields in a database are often null. Assuming that you have an InventoryDate field in a table, you could write code as follows:

If dt.Rows(0).Item("InventoryDate") Is DBNull.Value Then
    prod.InventoryDate = Nothing
Else
    prod.InventoryDate = _
          CType(dt.Rows(0).Item("InventoryDate"), Date)
End If

The If statement is required here because you cannot convert a DBNull to a date using CType. So you first need to ensure that it is not a null.

Use the Nullable structure any time you need to support nulls in a value type, such as an integer, Boolean, or date.

By adding properties to your classes, you provide your application with easy access to object data. This allows the user interface, for example, to display and update the data.

  • + Share This
  • 🔖 Save To Your Account