c# array.resize

Status
Not open for further replies.

office politics

It's all just 1s and 0s
Messages
6,555
Location
in the lab
i'm getting index out of bounds when trying to assign ok the the a array.

Code:
static void Main(string[] args)
        {
            string[] a = new string[0];

            Console.WriteLine(a.GetUpperBound(0) + 1);

            Array.Resize(ref a, a.GetUpperBound(0) + 1);

            a[0] = "ok";

            Console.WriteLine(a[0]);
        }
 
i'm getting index out of bounds when trying to assign ok the the a array.

Code:
static void Main(string[] args)
        {
            string[] a = new string[0];

            Console.WriteLine(a.GetUpperBound(0) + 1);

            Array.Resize(ref a, a.GetUpperBound(0) + 1);

            a[0] = "ok";

            Console.WriteLine(a[0]);
        }

Hi friend

This is my first post and feel that i am useful at C#.NET...

How familar are you with C#?

Index out of bounds means your trying to access a position within the array that is unavailable or not assigned anything..

The size of an array is ALWAYS "length - 1", as indexing starts at 0 within array, so what you are doing with the + 1 is incorrect. Additionally your array doesnt seem to have a size as you have assigned it 0, although as i said the indexing starts at 0, you still must assign a vaule <=1.

Let me know how you get on

All The Best

NeoMagic33
 
Neo is somewhat right. Except that you can set the array to 0 to start with. You're just resizing the array wrong. It isn't adding 1 to the size the way you were doing it.

Code:
static void Main(string[] args)
        {
            string[] a = new string[0];

            Console.WriteLine(a.GetUpperBound(0) + 1);

            Array.Resize(ref a, a.Length + 1);

            a[0] = "ok";

            Console.WriteLine(a[0]);
         }

That's what you need to use.
 
From a practical standpoint, if you find yourself needing to manually resize an array, use a List<T> instead. You can always call the 'ToArray()' method on the list if you need to pass the list as an array to some method.
 
I'm going to switch over to a list and use the add function. much easier.

jaeusm repped - edit, if i could - javascript error
 
Status
Not open for further replies.
Back
Top Bottom