133

Is there any method for creating a dynamic array in C#?

Siddiqui
  • 7,662
  • 17
  • 81
  • 129

9 Answers9

162

Take a look at Generic Lists.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Chris Van Opstal
  • 36,423
  • 9
  • 73
  • 90
  • 18
    The question (albeit short and undescriptive) isn't asking about a generic list - Question could be asking about `dynamic[]` https://msdn.microsoft.com/en-GB/library/dd264736.aspx (array of dynamic types) or `ExpandoObject` https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx I could -1 the answer for not mentioning these – Luke T O'Brien Jul 14 '16 at 12:31
  • 8
    @LukeTO'Brien, dynamics were introduced in C# 4.0, which was released a full year after this question was originally asked. OP was probably asking about a resizeable data structure like https://en.wikipedia.org/wiki/Dynamic_array – Brian Merrell Jan 23 '18 at 21:57
  • 10
    Answers consisting of only links to articles are unhelpful. There is no guarantee the link will remain active. – JamEngulfer Jul 22 '18 at 11:21
  • @JamEngulfer That's untrue. If his link text was "Look at this" with "this" linked, I'd agree with you. If you remove the link, and look at what's left, the OP's answer to "take a look at generic lists" is plenty of information to get any future reader googling.... – Lynn Crumbling Feb 25 '20 at 20:06
  • @LynnCrumbling And yet once again, the answer telling people to google it is the first result for "C# dynamic arrays". Thank god another person replied with a real answer. – JamEngulfer Oct 07 '21 at 23:29
  • @JamEngulfer For a new programmer, this most definitely answers the question, "how do I make a array dynamic?" Answer: "use a List instead; here's the link to MS docs" (I don't see any ref to Google.) Lots of upvotes agree. Feel free to downvote, if you haven't yet. – Lynn Crumbling Oct 08 '21 at 17:11
  • It doesn't even mention List. It's just a (fragile) link. And *you* said that "take a look at generic lists" is enough information for googling, but googling that just takes you back here. The second answer that gives a code example and explanation instead of lazily linking is far more valuable. And if you wonder why I'm commenting this now, it's because I needed to look it up for reference and encountered the same annoyance as I did three years ago. – JamEngulfer Oct 09 '21 at 22:04
  • 1
    @JamEngulfer "And if you wonder why I'm commenting this now, it's because I needed to look it up for reference and encountered the same annoyance as I did three years ago" -- Ha; fair enough. – Lynn Crumbling Oct 13 '21 at 02:01
99

Expanding on Chris and Migol`s answer with a code sample.

Using an array

Student[] array = new Student[2];
array[0] = new Student("bob");
array[1] = new Student("joe");

Using a generic list. Under the hood the List<T> class uses an array for storage but does so in a fashion that allows it to grow effeciently.

List<Student> list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));
Student joe = list[1];
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 2
    this example is half-bad, because we both talked about ArrayList – Migol Feb 27 '09 at 15:58
  • 27
    This answer is better than yours @Migol, because this show how to actually use the List<> instead of just mentioning it as a keyword. "half-bad" -> "half-good" -> good – fhugas Dec 08 '14 at 11:28
68

Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)

In this case you may use the ToArray() method after initiating your List dynamically

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");

string[] array = list.ToArray();

Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Mehdi LAMRANI
  • 11,289
  • 14
  • 88
  • 130
  • 1
    Not worth it, as long as you'are using indexer. – aaimnr Apr 15 '11 at 09:56
  • 3
    Ararys aren't more convenient (they offer subset of List interface) and offer almost the same performance, since List uses regular array underneath. Iteration for 6000000 elements: List/for: 1971ms Array/for: 1864ms ( Benchmark from http://stackoverflow.com/questions/454916/performance-of-arrays-vs-lists ) – aaimnr Apr 15 '11 at 10:03
  • 11
    If you *have* to pass an array to an interface then it *must* be an array. It's much easier to build a list and then make it into an array just before you pass it. I like this answer more than the others because it addresses the question! – Michael Stimson May 23 '14 at 00:55
  • Creating an array dynamically is not the same as creating a dynamic array. – jarmanso7 Mar 30 '23 at 12:14
36

List<T> for strongly typed one, or ArrayList if you have .NET 1.1 or love to cast variables.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
Migol
  • 8,161
  • 8
  • 47
  • 69
6

You can do this with dynamic objects:

var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };

foreach(var keyvalue in dynamicKeyValueArray)
{
    Console.Log(keyvalue.Key);
    Console.Log(keyvalue.Value);
}
Avner
  • 4,286
  • 2
  • 35
  • 42
1

Use the array list which is actually implement array. It takes initially array of size 4 and when it gets full, a new array is created with its double size and the data of first array get copied into second array, now the new item is inserted into new array. Also the name of second array creates an alias of first so that it can be accessed by the same name as previous and the first array gets disposed

1

Dynamic Array Example:

Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];

for (int i = 0; i < number; i++)
{
    arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
    Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
sydur.rahman21
  • 169
  • 1
  • 2
  • 8
1

you can use arraylist object from collections class

using System.Collections;

static void Main()
{
  ArrayList arr = new ArrayList();
}

when you want to add elements you can use

arr.Add();
julianstark999
  • 3,450
  • 1
  • 27
  • 41
0

This answer seems to be the answer you are looking for Why can't I do this: dynamic x = new ExpandoObject { Foo = 12, Bar = "twelve" }

Read about the ExpandoObject here https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=vs.110).aspx

And the dynamic type here https://msdn.microsoft.com/en-GB/library/dd264736.aspx

Community
  • 1
  • 1
Luke T O'Brien
  • 2,565
  • 3
  • 26
  • 38