How do I initialize an empty array in C#?

yogesh picture yogesh · Jan 4, 2012 · Viewed 570.2k times · Source

Is it possible to create an empty array without specifying the size?

For example, I created:

String[] a = new String[5];

Can we create the above string array without the size?

Answer

Oded picture Oded · Jan 4, 2012

If you are going to use a collection that you don't know the size of in advance, there are better options than arrays.

Use a List<string> instead - it will allow you to add as many items as you need and if you need to return an array, call ToArray() on the variable.

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();

If you must create an empty array you can do this:

string[] emptyStringArray = new string[0];