Information Technology Reference
In-Depth Information
Performing Other Calculations
Property accessors are not limited to just passing values back and forth from an associated
field—the get and set accessors can perform any—or no—computations. The only action
required is that the get accessor return a value of the property type.
For instance, the following example shows a valid (but probably useless) property that just
returns the value 5 when its get accessor is called. When the set accessor is called, it doesn't do
anything. The value of implicit parameter value is ignored.
public int Useless
{
set{ /* I'm not setting anything. */ }
get{ /* I'm just returning the value 5. */
return 5;
}
}
The following code shows a much more useful, realistic property, where the set accessor per-
forms filtering before setting the associated field. The set accessor sets field TheRealValue to the
input value—unless the input value is greater than 100. In that case, it sets TheRealValue to 100 .
int TheRealValue = 10; // The field
int MyValue // The property
{
set { // Sets the value of the field
TheRealValue = value > 100 // But makes sure it's not > 100
? 100
: value;
}
get { // Gets the value of the field
return TheRealValue;
}
}
Note In the preceding code sample, the syntax between the equals sign and the end of the statement
might look somewhat strange. That expression uses the conditional operator , which will be covered in greater
detail in Chapter 8.
The conditional operator is a ternary operator that evaluates the expression before the question mark, and,
if the expression evaluates to true , it returns the first expression after the question mark. Otherwise, it
returns the expression after the colon.
Search WWH ::




Custom Search