Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

404 Part III Designing the User Interface


class variables private—in other words, not available for inspection outside the class
module itself. These variables are sometimes call fields or backing fields because they
provide storage for properties.

Step 2: Create properties


  1. Below the variable declarations, type the following program statement, and then press
    ENTER:


Public Property FirstName() As String
This statement creates a property named FirstName, which is of type String, in your
class. This is all you need to do to implement a simple property. (A backing field is not
required .)
In Visual Studio 2008, what happens next is that Visual Basic creates a code template
for the remaining elements in the property declaration. These elements include a Get
block, which determines what other programmers see when they check the FirstName
property; a Set block, which determines what happens when the FirstName property is
set or changed; and an End Property statement, which marks the end of the property
procedure. However, in Visual Studio 2010, these elements are created automatically
when you use the Property statement. The process happens internally (you don’t
see it in the Code Editor), and in the documentation, it is referred to as the new
auto-implemented properties feature. This enables you to quickly specify a property
of a class without having to write Get and Set code blocks on your own.
Auto-implemented properties are very handy for those of us who create or
manipulate classes and properties often. However, there are situations in which you
cannot use auto-implemented properties but must instead use standard, or expanded,
property syntax (that is, the syntax that we used routinely in Visual Basic 2008). These
situations include the following scenarios:
o You need to add code to the Get or Set procedure of a property (for example,
when you are validating values in a Set code block).
o You want to make a Set procedure Private or a Get procedure Public.
o You want to create properties that are WriteOnly or ReadOnly.
o You want to add special parameterized properties.
o You want to place an attribute or Extensible Markup Language (XML) comment in
a hidden, private field.
Although these uses may seem advanced or esoteric at this point, they are important
enough that I want to teach you what the standard syntax for Get and Set code blocks
is. You may not need to use it at first, but as you create more advanced classes and
properties of your own, you may need to use it. (In addition, the Visual Studio Help
Free download pdf