When implementing a property, you might sometimes want to define a property that returns a calculated value, rather than just returning the value of an internal field.
Below is an example. We have a Dog class with Name and Age that each just wraps an internal field and are both read/write. We also define an AgeInDogYears property, which is read-only and returns the dog’s age in dog years.
The Age property is defined to encapsulate a private age field.
1
2
3
4
5
6
7
8
9
10
11
12
13
| // Age in human yearsprivate int age;public int Age{ get { return age; } set { age = value; }} |
The AgeInDogYears property is read-only and returns the calculated dog-year age.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| // Age in dog yearspublic float AgeInDogYears{ get { float dogYearAge; if (age < 1) dogYearAge = 0; else if (age == 1) dogYearAge = 10.5f; else dogYearAge = 21 + ((age - 2) * 4); return dogYearAge; }} |

