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?
int[] list = new int[5];
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[]) .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With