Chapter 26. Initializing Objects

Most of the time when you create an object, you need to initialize its properties. For example, you generally wouldn't create an Employee object without at least setting its FirstName and LastName properties. The following code shows how you might initialize an Employee object:

' Make an Employee named Alice.
Dim alice As New Employee()
alice.FirstName = "Alice"
alice.LastName = "Archer"
alice.Street = "100 Ash Ave"
alice.City = "Bugsville"
alice.State = "CO"
alice.Zip = "82010"
alice.EmployeeId = 1001
alice.MailStop = "A-1"

Though this is relatively straightforward, it is a bit tedious. Creating and initializing a bunch of Employees would take a lot of repetitive code. Fortunately, Visual Basic provides alternatives that make this task a little easier.

In this lesson you learn how to initialize an object's properties as you create it. You also learn how to make constructors that make initializing objects easier.

INITIALIZING OBJECTS

Visual Basic provides a simple syntax for initializing an object's properties as you create it. Create the object as usual with a New statement. Next add the keyword With and a pair of braces holding the property assignments. Each assignment should include a dot, a property name, an equals sign, and the value you want to give to the property.

For example, the following code creates an Employee object named Bob. The statements inside the braces initialize the object's properties.

' Make an Employee named Bob. Dim bob As New ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.