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 Review

Unexpected error

Whenever I run the program I keep on getting the eroor: Level.cs(15,21): error CS0161: `TreehouseDefense.Level.Play()': not all code paths re turn a value

Here is the code the error refers to. Could I get any help? I dont understand my code is exactly as it appears in the video.

public bool Play()
        {
            //Run until all invaders are dead or an invader reaches the end.
            int remainingInvaders = _invaders.Length;

            while(remainingInvaders > 0)
            {
                //Each tower has opportunity to fire on invaders
                foreach(Tower tower in Towers)
                {
                    tower.FireOnInvaders(_invaders);
                }

                //Counr and move iinvaders that are still active.
                remainingInvaders = 0;
                foreach(Invader invader in _invaders)
                {
                    if(invader.IsActive)
                    {
                        invader.Move();

                        if(invader.HasScored)
                        {
                            return false;
                        }

                        remainingInvaders++;
                    }
                }
            }
        }

For some reason it wont let me paste the beggining part so ill paste it here

public bool Play() { //Run until all invaders are dead or an invader reaches the end. int remainingInvaders = _invaders.Length;

Steven Parker
Steven Parker
231,268 Points

Your paste was OK, you just forgot to use Markdown formatting.

1 Answer

Steven Parker
Steven Parker
231,268 Points

Your function is defined to return a bool, which it does when it finds an invader that "HasScored".

But if it does not, it currently doesn't return anything, and that's causing the error.