How do I initialize an empty array in C#?
Solution 1
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];
Solution 2
Try this:
string[] a = new string[] { };
Solution 3
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.
Solution 4
You could inititialize it with a size of 0, but you will have to reinitialize it, when you know what the size is, as you cannot append to the array.
string[] a = new string[0];
Solution 5
There is not much point in declaring an array without size. An array is about size. When you declare an array of specific size, you specify the fixed number of slots available in a collection that can hold things, and accordingly memory is allocated. To add something to it, you will need to anyway reinitialize the existing array (even if you're resizing the array, see this thread). One of the rare cases where you would want to initialise an empty array would be to pass array as an argument.
If you want to define a collection when you do not know what size it could be of possibly, array is not your choice, but something like a List<T>
or similar.
That said, the only way to declare an array without specifying size is to have an empty array of size 0. hemant and Alex Dn provides two ways. Another simpler alternative is to just:
string[] a = { };
[The elements inside the bracket should be implicitly convertible to type defined, for instance, string[] a = { "a", "b" };
]
Or yet another:
var a = Enumerable.Empty<string>().ToArray();
Here is a more declarative way:
public static class Array<T>
{
public static T[] Empty()
{
return Empty(0);
}
public static T[] Empty(int size)
{
return new T[size];
}
}
Now you can call:
var a = Array<string>.Empty();
//or
var a = Array<string>.Empty(5);
yogesh
Updated on July 08, 2022Comments
-
yogesh almost 2 years
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?
-
Nick VanderPyle over 12 yearsExpanding on this answer, you can also init the array with items without specifying the size OR type, the compiler will infer either from the initializer: var a = new []{"a", "b", "c"}; This is still a strongly typed string array.
-
Kevin Brock over 12 yearsWhy do all that? At runtime you can define the array size from a variable normally:
int i = 5; string[] a = new string[i];
-
yogesh over 12 yearsUnhandled Exception: System.IndexOutOfRangeException: Index was outside the boun ds of the array. at ArrayClass.Main(String[] args). I faced this error after i changed my int[] variable = new int[]{}
-
Nope over 11 years@yogesh: That is strange. When for example writing
int[] variable = new int[]{}
and using it for example in a loop such asforeach (var s in variable){ Console.WriteLine(s);}
the code is compiled to:int[] args1 = new int[0];
andforeach (int num in args1){Console.WriteLine(num);}
. So there should be no difference between usingnew int[0]
andnew int[]{}
as both get compiled to the same code. -
radarbob almost 11 yearsWell, I guess with generics this appears to be obsolete.
-
rory.ap over 10 years@Oded -- string[] emptyStringArray = new string[0]; does not result in an empty array, does it? It looks like it's an array with one element where that element is null.
-
Oded over 10 years@roryap - No. It results in a
string[]
that has no elements. If you try to accessemptyStringArray[0]
, you will get aIndexOutOfRangeException
-
rory.ap over 10 years@Oded -- Thanks, I'm fairly new to C#. In VB, the index provided is the upper bound, not the number of elements.
-
realbart almost 10 yearsWhat would you consider better: var strings = new string[]{}; or var strings = new string[0]; BTW: I consider an empty array a perfectly valid default for method parameters: public void EditItems(IEnumerable<Item> toEdit, IEnumerable<long> toDelete = new long[]{})
-
nawfal about 9 yearsI cannot think of any use except when you got to pass an array as a parameter. There are a few cases in reflection where a method accepts an array of objects and you might want to pass an empty array to effect default action. I will edit my answer.
-
Ignacio Soler Garcia about 9 yearsYou for example have an interface implemented by several classes returning an IEnumerable and one of the implementations do not have elements for the method and returns an empty array for example.
-
nawfal about 9 years@IgnacioSolerGarcia I would return an array in that case if and only if it's an extremely performance critical application. I will say arrays are outdated and should be avoided if you can. See this by Lippert and this S.O. question
-
Ignacio Soler Garcia about 9 yearsHave in mind that the returned type is IEnumerable so the array is read-only and it is not intended to change. Why would I return a List in this case for example?
-
nawfal about 9 years@IgnacioSolerGarcia One,
IEnumerable
can be cast back to its original type, ie, array. Two, array is not truly read-only, items in any slot can be replaced with another instance. Three, of course you shouldn't return aList<T>
back if readonly-ness matter, you should return a genuine readonly type collection in .NET, say for eg,ReadOnlyCollection<T>
. The cases where arrays logically make sense are very very rare. Kindly go through that Lippert's link, it explains it beautifully. -
Ignacio Soler Garcia about 9 yearsI agree with what the the link explains about returning arrays as it really makes really sense. On the other way I think it would be extremely uncommon to cast an IEnumerable back to an array (even when this could be done). So all in all I think that returning an empty array in this case is safe and much more performant that returning an empty ReadOnlyCollection. Anyway I get your point, thanks.
-
nawfal about 9 yearsIf u don't worry about casting then returning a list would do the job too as the client only gets to operate on ienumerable. The performance benefits hardly matters imo. Logically arrays rarely makes sense. Sortedset, dictionary, ordereddictionary, queues, list, readonlycollection, immutablelist etc all translate to one specific use case or the other. What is an array? An editable but not removable, indexable collection of fixed size? Makes sense? It's a specialised low level structure which has its own quirks when you dig deep, esp with reflection. See the so q i linked to see array caveats.
-
vapcguy about 9 yearsA use case for an empty array is simple - when you want to fill it with objects and you don't know how many you'll be adding!
-
Sumner Evans about 9 yearsWon't this create a string array of length 1?
-
vapcguy about 9 yearsTrue, but it's cleared. And OP asked to declare the array without having to state a size - this fits that.
-
nawfal about 9 years@vapcguy 'when u don't know the how many' - this is the case when u use linearly growing structures. Any empty structure can be used in place of an array there. Unless u r dealing with legacy code which demands array.
-
vapcguy about 9 yearsAnd that deserves a downvote, why? OP meant not having to
specify
a size, not make an arraysizeless
. -
Sumner Evans about 9 yearsI did not downvote. If you add some more explanation to your answer, you might get some upvotes (or at least less get un-downvoted).
-
nawfal about 9 years@vapcguy I was the downvoter. I regret it. I have edited your answer to cancel my downvote. Your comment makes the question a bit dubious. Not sure if that is what OP meant.
-
vapcguy about 9 years@nawfal Thanks for the edit and downvote cancel. It's how I read what the OP posted, anyway. I actually use this method a lot, ex. when doing a
.Split()
on a semi-colon delimited string I'll set it equal toa
so thata
will be available at the level where I first instantiated it, usually at the top of the function, instead of having to use the array only where I do the.Split()
if I had to set it equal to astring[]
variable right there, like buried within someif...then
or loop within that. -
Jeppe Stig Nielsen about 8 years@GlennGordon Absolutely, but that is new as of C# version 3.0 (from 2007, with Visual Studio 2008). That version also allows another simple format with
var
, although only for local variables (not for fields). However in C# 2.0 (Visual Studio 2005) and earlier, you had to use the syntax of this answer (orstring[] a = new string[0];
). -
DavidRR over 7 yearsFor a practical need for the use of an empty array, see this answer to the question: "Create a REG_NONE empty value in the Windows Registry via C#."
-
Rick O'Shea over 7 yearsYou should use arrays rather than lists (ask Bjarne Stroustrup) and there is no defending the amount of boilerplate junk C# requires --which is why they continue to chip away at relieving users of doing what the language should be doing.
-
Oded over 7 years@RickO'Shea - C++ is not C#. Stroustrup knows his C++ - not so sure he knows his C# and the .NET GC. Not gonna go into a religious war with you.
-
DanielV over 5 yearsDefinitely an improvement for readability from:
Enumerable.Empty<T>().ToArray()
-
Keith about 5 yearsThe OP asked for an empty array. This array is not empty.
-
Jaider about 5 yearsIn .NET Core 2, there is already an extension for it,
arr = Array.Empty<string>();
-
ShloEmi about 5 yearsiirc, in .NetStandart [4.something] - there is also.
-
vapcguy about 5 years@Keith It's an array of one object that is an empty string. I think you're playing technicalities. There's an answer that was done after mine, here, that has
string[] array = {}
- perhaps that's better for you - though I wouldn't usearray
as a variable name since it's a keyword when capitalized. -
vapcguy about 5 yearsI would change
array
to justa
, asarray
is a keyword when capitalized. Just bad practice to use a keyword name as a variable name - even if the case is different. And basically the same as my answer except I hadString.Empty
in there. -
disklosr about 5 years1. array is not a c# keyword. Array is a class and not a keyword 2. "a" is also bad practice (maybe even worse a bad practice than using keywords)
-
vapcguy about 5 yearsBeing technical. Class, keyword, it defines an object type and is still bad. Why do you think
a
is bad? -
disklosr about 5 yearsBecause non-descriptive and one-letter variable names are bad practice because they don't convey the reason behind defining them. "array" is certainly a better name than "a". A better name would be "emptyArray".
-
l33t almost 5 yearsEven though this method is definitely preferred in most cases, it doesn't answer the original question. The OP wants to create an empty array.
Array.Empty<T>()
does not create an array. It returns a reference to a pre-allocated array. -
abzarak over 4 yearsThis is the accurate answer
-
Aaron Franke almost 3 yearsWhy is
EmptyArray<T>
a separate class instead of just having this be part ofArray<T>
? -
Nemo almost 3 yearsA list would be fast for insertion/deletion, but would be slower to index or iterate over, so it really depends on your needs. That being said, I'm sure Stroustrup is familiar with C#, he's quite an intelligent and upstanding person. I'm not quite sure why O'Shea brought him up here.
-
Oded almost 3 years@Nemo - are you sure about the indexing and iteration? Why not test it (benchmarkdotnet can help here)?
-
0xF almost 3 yearsThis answer starts very well by explaining, that arrays must have a size. Unfortunately later it reinvents the wheel instead of using .NET
Array.Empty<T>()
. -
nawfal almost 3 years@0xF Fortunately
Array.Empty<T>()
wheel had not been invented when I wrote this answer :) -
0xF almost 3 years@nawfal
Array.Empty<T>()
appeared in .NET Framework 4.6, so one year after your answer. Apologies!