Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of an unknown length in C#

Tags:

arrays

c#

I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?

like image 965
UnkwnTech Avatar asked Mar 01 '09 06:03

UnkwnTech


People also ask

How do you declare an array of unknown size?

int[] list = new int[5];

Can we define array without size in C?

You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) .

Can you create an array with unknown size?

You can dynamically create a array. But You can not change the size of array once it is declared. You need to create new array of bigger size and then copy the content of old array into it.

How do you find the length of an array in C?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.


1 Answers

Arrays must be assigned a length. To allow for any number of elements, use the List class.

For example:

List<int> myInts = new List<int>(); myInts.Add(5); myInts.Add(10); myInts.Add(11); myInts.Count // = 3 
like image 101
Samuel Avatar answered Sep 22 '22 18:09

Samuel