The body of the get accessor resembles that of a method. It must return a value of the property type. The execution of the get accessor is equivalent to reading the value of the field. For example, when you are returning the private variable from the get accessor and optimizations are enabled, the call to the get accessor method is inlined by the compiler so there is no method-call overhead. However, a virtual get accessor method cannot be inlined because the compiler does not know at compile-time which method may actually be called at run time. The following is a get accessor that returns the value of a private field name:
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
}
}
When you reference the property, except as the target of an assignment, the get accessor is invoked to read the value of the property. For example:
Person person = new Person();
//...
System.Console.Write(person.Name); // the get accessor is invoked here
The get accessor must end in a return or throw statement, and control cannot flow off the accessor body.
It is a bad programming style to change the state of the object by using the get accessor. For example, the following accessor produces the side effect of changing the state of the object every time that the number field is accessed.
private int number;
public int Number
{
get
{
return number++; // Don't do this
}
}
The get accessor can be used to return the field value or to compute it and return it. For example:
class Employee
{
private string name;
public string Name
{
get
{
return name != null ? name : "NA";
}
}
}
In the previous code segment, if you do not assign a value to the Name property, it will return the value NA.