HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How do I initialize an empty array in C#?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
emptyinitializehowarray

Problem

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?

Solution

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 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();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();


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

string[] emptyStringArray = new string[0];


As of .NET 4.6, the following would be recommended for an empty array:

String[] a = Array.Empty();


With C# 12/.NET8, there's an even more succinct way (using collection expressions):

String[] a = [];

Code Snippets

var listOfStrings = new List<string>();

// do stuff...

string[] arrayOfStrings = listOfStrings.ToArray();
string[] emptyStringArray = new string[0];
String[] a = Array.Empty<string>();
String[] a = [];

Context

Stack Overflow Q#8727146, score: 557

Revisions (0)

No revisions yet.