Information Technology Reference
In-Depth Information
Properties
A property is a member that represents an item of data in a class instance or class.
Using a property appears very much like writing to, or reading from, a field. The syntax is
the same. For example, the following code shows the use of a class called MyClass that has both
a public field and a public property. From their usage, you cannot tell them apart.
MyClass mc = new MyClass();
mc.MyField = 5; // Assigning to a field
mc.MyProperty = 10; // Assigning to a property
WriteLine("{0} {1}", mc.MyField, mc.MyProperty); // Read field and property
A property, like a field, has the following characteristics:
￿
It is a named class member.
￿ t has a type.
￿
It can be assigned to and read from.
Unlike a field, however, a property is a function member .
￿
It does not allocate memory for data storage!
￿
It executes code.
A property is a named set of two matching methods called accessors .
￿The set accessor is used for assigning a value to the property.
￿The get accessor is used for retrieving a value from the property.
Figure 6-7 shows representations of a property. The code on the left shows the syntax of
declaring a property named MyValue , of type int . The figure on the right shows how I will
graphically represent properties in this text. The accessors are shown sticking out the back,
because, as you shall soon see, they are not directly callable.
Figure 6-7. An example property of type int, named MyValue
Search WWH ::




Custom Search