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

CS0161: Not all code paths return a value with Foreach Loop and conditional statement

Not sure what I'm missing here. I have an "else{}" statement to cover any untested scenarios within the Foreach Loop used to check the values against the previous value tested. So, I'm not sure what I'm missing. I believe the flaw is in the "RepeatDetector.cs" file.

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

}
RepeatDetector.cs
namespace Treehouse.CodeChallenges
{

    public class RepeatDetector : SequenceDetector
    {
        private int checkOne;
        private int checkTwo; 
        private bool checkReturn;
        public override bool Scan(int[] sequence)
        {
            checkOne = 0;
            checkTwo = 0;
            foreach (int check in sequence)
            {
                checkTwo = checkOne;
                checkOne = check;
                if (checkTwo == checkOne)
                {
                    return true;                
                }
                else
                {
                    return false;
                }

            }

        }
    }

}

4 Answers

Steve Agusta
Steve Agusta
6,221 Points

try using a for loop instead to make sure you're looping through the array and think of how you might check the value of each index in the array, then you can make the comparison. Also, you can do it the way you have here, using a bool variable to return the value, but in the example you've shown, you're not actually returning that variable. Or you can just return the true/false value from within the loop.

Thanks Steve. That helped. I was thinking that each item in the array needed to return something not just if any of the items in the array were duplicates then the whole thing needed to return true.

Steve Agusta
Steve Agusta
6,221 Points

Sure, no problem. No, each item doesn't ned to return a value, we're just checking each value in the array against the value before it to see if they are in sequence. Have you got it now, or do you need a hint?

all good.