X hits on this document

PDF document

“Beginning Visual C# 2005 Express Edition Video Series” - page 49 / 73

157 views

0 shares

0 downloads

0 comments

49 / 73

Object Lifetime

Like many living objects in the real world, code objects have a birth, a life and a death. You can write code that executes when an object is born and when it is about to die.

We've talked about instantiating an object from its class definition, which means we take the Class and create an object from it. But we haven't told the entire story. Let’s look at what happens when we create an instance of a class, and we'll talk about what happens after we finish using it.

Introducing Constructors

First of all, classes have Constructors, which is a special method that allows you to initialize your fields, or whatever else you may want to do when your object is first created. In C#, you create a Constructor using the same name as the class in the form of a method. For example, this is what the constructor for the Car class would look like:

C#:

public class Car {

public Car() { make = "Unknown"; model = "Unknown"; elapsedMileage =0;

}

}

Here we've set our private fields to default values. The Constructor gets called whenever the new keyword is used in association with our class. Here’s an example of code you might

Supplemental Readings for the Express Edition Videos Copyright © 2005 LearnVisualStudio.NET



Document info
Document views157
Page views157
Page last viewedSun Dec 04 04:53:42 UTC 2016
Pages73
Paragraphs821
Words15988

Comments