Information Technology Reference
In-Depth Information
Properties and Associated Fields
A property is often associated with a field. A common practice is to encapsulate a field in a class
by declaring it private , and declaring a public property to give controlled access to the field
from outside the class.
For example, the following code uses the public property MyValue to give controlled access
to private field TheRealValue .
class C1
{
private int TheRealValue = 10; // Field: memory allocated
public int MyValue // Property: no memory allocated
{
set{ TheRealValue = value; } // Sets the value of field TheRealValue
get{ return TheRealValue; } // Gets the value of the field
}
}
class Program
{
static void Main()
{
Read from the property as if it were a field
C1 c = new C1();
Console.WriteLine("MyValue: {0}", c.MyValue);
c.MyValue = 20; Use assignment to set value of property
Console.WriteLine("MyValue: {0}", c.MyValue);
}
}
Search WWH ::




Custom Search