C# C# Collections Lists Lists

index out of range

iam returning the list of integers {1,2,4,8,16} and i got index out of range error. I think index should start from 0 so that it can represent 1 as 2powerd by 0. what is the wrong then in my code??

MathHelpers.cs
using System;
using System.Collections.Generic;
namespace Treehouse.CodeChallenges
{
    public class MathHelpers
    {
       public static List<int> GetPowersOf2(int number)
        {
        List<int> list =  new List<int>();
        for(int i =0; i<=number; i++)
        {
            list[i] = (int) Math.Pow(2,i) ;
        }
        return list;
        }
    }

}
Daniel Breen
Daniel Breen
14,636 Points

I answered below, but your question made me wonder about List Capacity Initialization as well. My first thought was that you could initialize the List capacity...

List<int> list = new list<int>(number + 1)

...then do as you did...

list[i] = (int) Math.Pow(2,i) ;

However, I found from this stack overflow answer that it doesn't quite work like that.

https://stackoverflow.com/a/15843509/6843314

"There is List<T> constructor which takes an int as a parameter for initiall list capacity, but it does not actually creates that number of elements within a list, so this will throw ArgumentOutOfRangeException... "

So my answer below is the simple solution, but there's useful info in that stack overflow answer.

1 Answer

Daniel Breen
Daniel Breen
14,636 Points

Your list doesn't know what size it is.

Remember that a List is just a fancy container for an array.

try list.Add((int) Math.Pow(2,i)); instead of list[i] = (int) Math.Pow(2,i);

The .Add() will resize the array for you and prevent IndexOutOfRangeException