
Initializing Objects
Most of the time when you create an object, you need to initialize its properties. You generally
wouldn’t create an
Employee object without at least setting its FirstName and LastName prop-
erties. The following code shows how you might initialize an
Employee object:
// Make an Employee named Alice.
Employee alice = 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 C# 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, and how to make destructors
that clean up after an object.
INITIALIZING OBJECTS
C# provides a simple syntax for initializing an object’s properties as you create it. Create the
object as usual but follow the
new keyword and the class’s name with braces. Inside the braces,
place comma-separated statements that initialize the object’s properties.
For example, the following code creates an
Employee object named Bob. The statements inside
the braces initialize the object’s proper ...