Resize array in C # later in program

I'm not sure if this is possible in C # but I have a variable defined in

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

Then in the program I want to be able to resize in the program before the main routines start on it and do some calculations

Since I like to test using sets of numbers and sizes of arrays, I would like to be able to change the size of the array for each test (but this array is not associated with one procedure, its global variable, which must be mutable.

Since the whole program in different parts uses this array (under various functions), how should I put this part

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

So that he resize this global variable size?

+4
source share
4 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 a new array.

Update: I don't like Array.Resize - it does not resize the array (as the method name suggests), it creates a new array and replaces the link:

  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(); } 
+14
source

as icemanind recommended - consider using a List array, but as a best practice, make sure you initialize the array to a reasonable amount. i:

 List<string> myList = new List<string>(10); // initial length is 10 

the advantage is that performance and space allocation are predefined, and that doesnโ€™t mean that it has to recreate the collection every time you add an item to it, because it will use the existing allocated amount until it reaches, and then will increase it internally.

0
source
  class Program { static void Main(string[] args) { var myArr = new int[5] { 1, 2, 3, 4, 5 }; Array.Resize(ref myArr, 10); for (int i = 0; i < myArr.Length; i++) { Console.WriteLine(" [{0}] : {1}", i, myArr[i]); } Console.ReadLine(); } } 
0
source

Use Array.Resize() to resize the array,

http://msdn.microsoft.com/en-us/library/bb348051.aspx

For instance:

  var intArray = new int[5] { 1, 2, 3, 4, 5 }; Array.Resize(ref intArray, 10); 
-1
source

Source: https://habr.com/ru/post/1260284/


All Articles