How can I define a dynamic array in C#?
+6
A:
C# doesn't provide dynamic arrays. Instead, it offers List class which works the same way.
To use lists, write at the top of your file:
using System.Collections.Generic;
And where you want to make use of a list, write (example for strings):
List<string> mylist = new List<string>();
mylist.Add("First string in list");
Alexander Shvetsov
2009-12-19 10:30:02
This isn't really an array per se, but rather a collection. Although it can be accessed like an array, in memory it's stored as a linked list.
Daniel T.
2009-12-19 10:33:47
I don't think a List is internally stored as a linked list. It has to be as an array.
Frederick
2009-12-19 10:36:28
No, a List is a linked list internally. What makes you think it must be an array?
Anon.
2009-12-19 10:37:59
`List<T>` is using an array internally. You can find this either with Reflector or in the documentation.
Joey
2009-12-19 10:39:10
Anon: The defined performance characteristics for example. Each List method such as Add state their time complexity.
Joey
2009-12-19 10:40:56
Generic List uses an array internally, not a linked list. @Anon: What makes you think it's a linked list? Use reflector and check it for yourself.
Groo
2009-12-19 11:09:44
List<T> is not a linked list. LinkedList<T> is a linked list.
cfern
2009-12-19 13:57:34
list != array j
Hellfrost
2009-12-19 14:07:17
A:
like so
int nSize = 17;
int[] arrn = new int[nSize];
nSize++;
arrn = new int[nSize];
Hellfrost
2009-12-19 11:48:36
+1
A:
Take a look at Array.Resize if you need to resize an array.
// Create and initialize a new string array.
String[] myArr = {"The", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"};
// Resize the array to a bigger size (five elements larger).
Array.Resize(ref myArr, myArr.Length + 5);
// Resize the array to a smaller size (four elements).
Array.Resize(ref myArr, 4);
Alternatively you could use the List class as others have mentioned. Make sure you specify an initial size if you know it ahead of time to keep the list from having to resize itself underneath. See the remarks section of the initial size link.
List<string> dinosaurs = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
If you need the array from the List, you can use the ToArray() function on the list.
string[] dinos = dinosaurs.ToArray();
SwDevMan81
2009-12-19 14:57:01