#233 – Returning a Result from an Instance Method

You can return a result from an instance method by declaring its return type to be something other than void.  An instance method can return a result of any type, including both value types and reference types.

In the example below, the Dog.GiveAgeInHumanYears method returns a float value.

    public class Dog
    {
        public string Name;
        public int Age;

        public float GiveAgeInHumanYears()
        {
            float ageInHuman;

            // 10.5 yrs for 1st 2 yrs, 4 yrs for each thereafter
            if (Age < 1)
                ageInHuman = 0;
            else if (Age == 1)
                ageInHuman = 10.5f;
            else
                ageInHuman = 21 + ((Age - 2) * 4);

            return ageInHuman;
        }
    }

The new value is calculated based on the value of the Age field–which stores the age of the Dog instance for which this method was called.  The calculated human age is then returned as the result, using the return statement.

Using this method:

    // Assuming that Jack is 16 and Kirby is 13
    Console.WriteLine(jack.GiveAgeInHumanYears());   // 77
    Console.WriteLine(kirby.GiveAgeInHumanYears());  // 65
Advertisement

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: