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#

olu adesina
olu adesina
23,007 Points

c# i keep getting an out of bounds exception for my build stairs challenge

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace test
{
 /*return an array of stairs like this if i entered 2 into my argument
[
"**",
"****",
"******"
]*/


    class Program
    {


        static void Main(string[] args)
        {
             string[] TowerBuilder(int nFloors)
            { string[] tower = new string[0];
                string Stars = "";
                int i = 0;
                while (nFloors>0)
                {

                    Stars += "**" ;
                    tower[i] = Stars;
                    nFloors -=1;  // out of bounds exception here
                    i++;

                }
                return tower;
            }

            Console.WriteLine(TowerBuilder(9));
            Console.ReadLine();

        }
    }


}

1 Answer

Erik Gabor
Erik Gabor
6,427 Points

Hi

You have declared bellow an array of strings of 0 size

string[] tower = new string[0];

You should declare a bigger length

string[] tower = new string[nFloors];

or use generics like lists if you wanna go dynamic

List<string> tower =new List<string>();

Also I would have declared TowerBuilder as a class method inside the Program class.