Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
A class groups a set of values and a set of operations. The values and the operations of a class are called its members. Fields implement the values and methods implement the operations.
Suppose we wish to define a class to represent complex numbers . The Complex class definition shown in Program illustrates how this can be done. Two fields, real and imag, are declared. These represent the real and imaginary parts of a complex number (respectively). Program also defines two properties, Real and Imag, each of which provide get and set accessors that can be used to access the real and imaginary parts of a complex number (respectively).
Program: Complex class fields, Real and Imag properties.
Every object instance of the Complex class contains its own fields. Consider the following variable declarations:
Complex c = new Complex(); Complex d = new Complex();Both c and d refer to distinct instances of the Complex class. Therefore, each of them has its own real and imag field. The fields of an object are accessed using the dot operator. For example, c.real refers to the real field of c and d.imag refers to the imag field of d.
Program also defines the properties Real and Imag. In general, a property is an attribute of an instance of the class. Again, the dot operator is used to specify the object on which the operation is performed. For example, c.Real = 1.0 invokes the set accessor of the Real property on c and Console.Writeline(d.Imag) invokes get accessor of the Imag property on d.