#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;
                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