How do I initialize an empty array in C#?
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];
In .NET 4.6 the preferred way is to use a new method, Array.Empty
:
String[] a = Array.Empty<string>();
The implementation is succinct, using how static members in generic classes behave in .Net:
public static T[] Empty<T>(){ return EmptyArray<T>.Value;}// Useful in number of places that return an empty byte array to avoid// unnecessary memory allocation.internal static class EmptyArray<T>{ public static readonly T[] Value = new T[0];}
(code contract related code removed for clarity)
See also:
Array.Empty
source code on Reference Source- Introduction to
Array.Empty<T>()
- Marc Gravell - Allocaction, Allocation, Allocation - my favorite post on tiny hidden allocations.