Lesson 24

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 properties. 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 fairly 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 define 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 and initializes an Employee object named alice similar to the one created in the previous code. The statements inside the braces initialize the object's properties. ...

Get C# 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.