Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize an empty array in C#?

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?

like image 960
yogesh Avatar asked Jan 04 '12 12:01

yogesh


People also ask

How do you initialize an empty array?

To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.

How do you initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

Can you initialize an array to null?

Array elements are initialized to 0 if they are a numeric type ( int or double ), false if they are of type boolean , or null if they are an object type like String .


1 Answers

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];  
like image 162
Oded Avatar answered Oct 05 '22 14:10

Oded