#248 – Implementing a Property that Returns a Calculated Value

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.

        // Age in human years
        private int age;
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }

The AgeInDogYears property is read-only and returns the calculated dog-year age.

        // Age in dog years
        public 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;
            }
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: