Home > Articles > Programming > Visual Basic

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020