Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Methods Method Overloading

Li Yu
Li Yu
2,067 Points

What are the differences between these two methods?

This challenge goes like the following: Add another method named EatFly that takes two integer parameters(distanceToFly, flyReactionTime) and returns a boolean value. Though I overcome the challenge, I still want to ask what are the differences between "method A" and "method B", and why couldn't I write "method B" only?

Frog.cs
namespace Treehouse.CodeChallenges
{
    class Frog
    {
        public readonly int TongueLength;
        public readonly int ReactionTime;

        public Frog(int tongueLength, int reactionTime)
        {
            TongueLength = tongueLength;
            ReactionTime = reactionTime;
        }

        public bool EatFly(int distanceToFly) // Let this method over here be A ...
        {
            return TongueLength >= distanceToFly;
        }

        public bool EatFly(int distanceToFly, int flyReactionTime)  //...and let this method over here be B.
        {
            return (TongueLength >= distanceToFly) && (ReactionTime <= flyReactionTime);

        }
    }
}

2 Answers

Method A is making a decision (e.g.; returning a Boolean True or False). This decision is based on whether

TongueLength >= distanceToFly

Method B is making same decision (e.g.; returning a Boolean True or False). But this decision is based on whether

TongueLength >= distanceToFly

and (&&)

(ReactionTime <= flyReactionTime)

so ... both methods are to help the calling parting make a T/F decision, but B is using more information than A to make this same decision.

If this answers your question, please mark the question as answered.

Thanks

In addition to Mark's explanation this demonstrates overloading which is the ability to have multiple methods that share the same name but have different parameters. Not to be confused with overriding which overrides an inherited method and must have the same parameters.