Question:
I want the struct array to grow and shrink dynamically in c#.?
Ahmad
2009-08-25 05:50:52 UTC
I am trying to find help from the internet but i the help which is available on the internet is very professional and i can't understand properly.
Kindly Please help me and guide me because i have to implement this in of the program.
Four answers:
2009-08-25 07:34:28 UTC
Try using a list - you can create new structures and then add them to the list. Works much better than an array.



See http://www.c-sharpcorner.com/UploadFile/camurphy/csharpLists03302006170209PM/csharpLists.aspx for details.
2009-08-25 06:16:40 UTC
I don't think you can within a struct, however you could just have the struct contain a pointer to a block of data that is handled as an array.



I'm not particularly 'up' on C++ but I'm sure that would cause all sorts of memory management issues that you'd need to cover first though.
▐▀▀♦▀▀▌ ♦Oprah♦ ▐▄▄♦▄▄▌
2009-08-25 06:08:08 UTC
Arrays cannot be resized dynamically. You will need to allocate a new array, and copy the contents of the old array to the new one.



This function helps copying the elements:

System.Array.Copy(oldArray, newArray, length);
tbshmkr
2009-08-25 08:34:21 UTC
array.resize == Read source!!

=

http://dotnetperls.com/array-resize

// Example = = http://dotnetperls.com/array-resize

using System;



class Program

{

static void Main()

{

// Initialize an array with 5 elements.

char[] arr = new char[5];

arr[0] = 'p';

arr[1] = 'y';

arr[2] = 't';

arr[3] = 'h';

arr[4] = 'o';



// We need an array with 6 elements!

// Use Array.Resize to make it bigger.

Array.Resize(ref arr, 6);



// Assign the last element.

arr[5] = 'n';



// Display the array

Console.WriteLine(new string(arr));

}

}



=== Output of the program ===

(Has 6 elements now.)



python

- - -

Another example

- http://www.source-code.biz/snippets/csharp/1.htm


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...