C# – How to initialize an empty array in C#

arrayscinitialization

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?

Best Answer

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];