Information Technology Reference
In-Depth Information
Instance Class Members
Class members can be associated with an instance or with the class. By default, members are
associated with an instance. You can think of each instance of a class as having its own copy of
each class member. These members are called instance members .
Changes to the value of one instance field do not affect the values of the members in any
other instance. So far, the fields and methods you've looked at have all been instance fields and
instance methods.
For example, the following code declares a class D with a single integer field Mem1 . Main cre-
ates two instances of the class. Each instance has its own copy of field Mem1 . Changing the value
of one instance's copy of the field does not affect the values of the other instances' copies.
Figure 6-2 shows the two instances of class D .
class D
{
public int Mem1;
}
class Program
{
static void Main()
{
D d1 = new D();
D d2 = new D();
d1.Mem1 = 10; d2.Mem1 = 28;
Console.WriteLine("d1 = {0}, d2 = {1}", d1.Mem1, d2.Mem1);
}
}
This code produces the following output:
d1 = 10, d2 = 28
Figure 6-2. Two instances with instance data members
Search WWH ::




Custom Search