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

Joshua Thao
Joshua Thao
6,439 Points

Index outside of bounds

Why is it saying my index is out of bounds? I dont know how to fix it.

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[] sequence)
        {
            for (int i = 0; i < sequence.Length; i++)
            {
                if (sequence[i] == sequence[i + 1])
                {
                    return true;
                }
            }
            return false;
        }
    }
}

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Joshua Thao ! I received your request for assistance. The problem here is in your for loop. It's going just a tad too far because you also have to check what the next index is. Imagine that we have an array [3, 5, 10, 20]. The length of that would be 4. You say to check while it's less than 4 and then check the next index also. That would mean it would stop at an index of 3. The element with the index of 3 is 20. But what is the element at index + 1 (or 4)? It's out of bounds. To mitigate this you need to stop just one shy of the end.

So where you wrote:

i < sequence.Length

That should be:

i < sequence.Length - 1

Because you still need to be able to access one more than i as well.

Hope this helps! :sparkles: