Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Objects Methods Methods

Atanu Mondal
Atanu Mondal
1,976 Points

getting compile error while calling EatFly method with if condition checking

while compiling the program i am getting a compile error as Treehouse.CodeChallenges.Frog.EatFly(int)': not all code paths return a value Compilation failed: 1 error(s), 0 warnings

below is my complete code

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

        public Frog(int tongueLength)
        {
            TongueLength = tongueLength;
        }

        public bool EatFly(int distanceToFly)
        {
            if(TongueLength >= distanceToFly)
            {
                return true;
            }
        }
    }
}

if i dont use if statement it runs correctly

return TongueLength >= distanceToFly;

can anyone explain why?

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

        public Frog(int tongueLength)
        {
            TongueLength = tongueLength;
        }

        public bool EatFly(int distanceToFly)
        {
            if(TongueLength >= distanceToFly)
            {
                return true;
            }
        }
    }
}

1 Answer

Steven Parker
Steven Parker
216,012 Points

Directly returning the result of the comparison always gives a boolean value, which is consistent with the function definition. This is also an optimum solution to the challenge.

When you add the IF condition, you're only returning a value when the condition is met. To meet the requirements of the definition, you'd also need to a return a value when the condition is not met.