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# Intermediate C# Polymorphism Virtual Methods

Nathan Reinauer
Nathan Reinauer
2,097 Points

Not all code paths return a value?

I keep getting an error about there being paths that don't return a value. I've tried a number of things, including wrapping my for loop with if statements inside another if statement to make sure everything returns something--even if the array is totally empty--but that's not working either.

SequenceDetector.cs
namespace Treehouse.CodeChallenges
{
    class SequenceDetector
    {
        public virtual bool Scan(int[] sequence)
        {
            return true;
        }
    }


}
RepeatDetector.cs
namespace Treehouse.CodeChallenges
{   
    class RepeatDetector : SequenceDetector
    {
        public override bool Scan(int[] repeat)
        {
            if(repeat.Length > 0)
            {
                for(int i = 0; i < repeat.Length; i++)
                {
                    if(repeat[i] == repeat[i - 1])
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }

        }
    }
}

1 Answer

Steven Parker
Steven Parker
231,248 Points

:point_right: Always return a value somewhere outside of conditional blocks.

The compiler may not look deeply enough to see if your conditionals cover all cases. But in this case it's clear that if the method were called with a repeat.Length of 0, no return statement would be executed.

To avoid the issue, take advantage of the fact an else is never necessary when the if contains a return. So where you have something like this:

if (<some comparison>)
{
    return true;
}
else
{
    return false;
}

Do this instead:

if (<some comparison>)
{
    return true;
}
return false;

Actually, in this trivial case it's even more efficient to write it this way without any conditionals:

return <some comparison>;