Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize array in C# later in the program

Tags:

arrays

c#

I am not sure if this is possible in c# but i'm having a variable defined in

 public partial class Form1 : Form
 {...
   ...
    #region used variables
    public ulong[] logP = {0,0,0,0,0,0,0,0}
  ....
  ..

Then later in the program i want have an option to adjust the size in the program before the main routines will launch over it and do some calculations

Because i like to test with vaious sets of numbers and array sizes i would like to have an option to resize the array, for each test (but this array isnt bound to a single procedure, its a global variable that needs to be resizable.

As the whole program at various parts is using this array, (under various functions) how should i put this part

    ulong [] sumP = new ulong[numericupdown.valeu];

So that it would change this global variable size ?

like image 842
user613326 Avatar asked Dec 04 '22 09:12

user613326


1 Answers

You cannot resize an array; you must declare a new array of the desired size and copy the contents of the original array into the new array.

Update: I don't like Array.Resize - it doesn't resize the array (as the method name would suggest), it creates a new array and replaces the reference:

    static void Main(string[] args)
    {
        int[] a1 = new int[] { 1, 2, 3 };
        int[] a2 = a1;

        Console.WriteLine("A1 Length: {0}", a1.Length); // will be 3
        Console.WriteLine("A2 Length: {0}", a2.Length); // will be 3
        Array.Resize(ref a1, 10);
        Console.WriteLine("A1 Length: {0}", a1.Length); // will be 10
        Console.WriteLine("A2 Length: {0}", a2.Length); // will be 3 - not good

        Console.ReadLine();
    }
like image 73
Moho Avatar answered Jan 03 '23 22:01

Moho