Книга: C# 2008 Programmer
Creating an Instance of a Class (Object Instantiation)
Creating an Instance of a Class (Object Instantiation)
A class works like a template. To do anything useful, you need to use the template to create an actual object so that you can work with it. The process of creating an object from a class is known as instantiation.
To instantiate the Contact
class defined earlier, you first create a variable of type Contact
:
Contact contact1;
At this stage, contact1
is of type Contact
, but it does not actually contain the object data yet. For it to contain the object data, you need to use the new keyword to create a new instance of the Contact
class, a process is known as object instantiation:
contact1 = new Contact();
Alternatively, you can combine those two steps into one, like this:
Contact contact1 = new Contact();
Once an object is instantiated, you can set the various members of the object. Here's an example:
contact1.ID = 12;
contact1.FirstName = "Wei-Meng";
contact1.LastName = "Lee";
contact1.Email = "[email protected]";
You can also assign an object to an object, like the following:
Contact contact1 = new Contact();
Contact contact2 = contact1;
In these statements, contact2
and contact1
are now both pointing to the same object. Any changes made to one object will be reflected in the other object, as the following example shows:
Contact contact1 = new Contact();
Contact contact2 = contact1;
contact1.FirstName = "Wei-Meng";
contact2.FirstName = "Jackson";
//---prints out "Jackson"---
Console.WriteLine(contact1.FirstName);
It prints out "Jackson" because both contact1
and contact2
are pointing to the same object, and when you assign "Jackson" to the FirstName
property of contact2
, contact1
's FirstName
property also sees "Jackson".
- Classes
- Defining a Class
- Static Classes
- InterBase Classic Server под Linux
- Каталог BIN в InterBase Classic Server для Linux
- Classic
- Classic vs SuperServer
- Рекомендации по выбору архитектуры: Classic или SuperServer?
- Эффективное взаимодействие процессов архитектуры Classic Server
- Yaffil Classic Server - замена InterBase Classic 4.0
- SERVER PRIORITY CLASS
- CLASSIFY target