How do I initialize an empty array in C#?

670,093

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:

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);
Share:
670,093
yogesh
Author by

yogesh

Updated on July 08, 2022

Comments

  • yogesh
    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
    Nick VanderPyle over 12 years
    Expanding 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
    Kevin Brock over 12 years
    Why do all that? At runtime you can define the array size from a variable normally: int i = 5; string[] a = new string[i];
  • yogesh
    yogesh over 12 years
    Unhandled 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
    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 as foreach (var s in variable){ Console.WriteLine(s);} the code is compiled to: int[] args1 = new int[0]; and foreach (int num in args1){Console.WriteLine(num);}. So there should be no difference between using new int[0] and new int[]{} as both get compiled to the same code.
  • radarbob
    radarbob almost 11 years
    Well, I guess with generics this appears to be obsolete.
  • rory.ap
    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
    Oded over 10 years
    @roryap - No. It results in a string[] that has no elements. If you try to access emptyStringArray[0], you will get a IndexOutOfRangeException
  • rory.ap
    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
    realbart almost 10 years
    What 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
    nawfal about 9 years
    I 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
    Ignacio Soler Garcia about 9 years
    You 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
    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
    Ignacio Soler Garcia about 9 years
    Have 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
    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 a List<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
    Ignacio Soler Garcia about 9 years
    I 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
    nawfal about 9 years
    If 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
    vapcguy about 9 years
    A 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
    Sumner Evans about 9 years
    Won't this create a string array of length 1?
  • vapcguy
    vapcguy about 9 years
    True, but it's cleared. And OP asked to declare the array without having to state a size - this fits that.
  • nawfal
    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
    vapcguy about 9 years
    And that deserves a downvote, why? OP meant not having to specify a size, not make an array sizeless.
  • Sumner Evans
    Sumner Evans about 9 years
    I 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
    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
    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 to a so that a 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 a string[] variable right there, like buried within some if...then or loop within that.
  • Jeppe Stig Nielsen
    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 (or string[] a = new string[0];).
  • DavidRR
    DavidRR over 7 years
    For 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
    Rick O'Shea over 7 years
    You 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
    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
    DanielV over 5 years
    Definitely an improvement for readability from: Enumerable.Empty<T>().ToArray()
  • Keith
    Keith about 5 years
    The OP asked for an empty array. This array is not empty.
  • Jaider
    Jaider about 5 years
    In .NET Core 2, there is already an extension for it, arr = Array.Empty<string>();
  • ShloEmi
    ShloEmi about 5 years
    iirc, in .NetStandart [4.something] - there is also.
  • vapcguy
    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 use array as a variable name since it's a keyword when capitalized.
  • vapcguy
    vapcguy about 5 years
    I would change array to just a, as array 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 had String.Empty in there.
  • disklosr
    disklosr about 5 years
    1. 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
    vapcguy about 5 years
    Being technical. Class, keyword, it defines an object type and is still bad. Why do you think a is bad?
  • disklosr
    disklosr about 5 years
    Because 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
    l33t almost 5 years
    Even 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
    abzarak over 4 years
    This is the accurate answer
  • Aaron Franke
    Aaron Franke almost 3 years
    Why is EmptyArray<T> a separate class instead of just having this be part of Array<T>?
  • Nemo
    Nemo almost 3 years
    A 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
    Oded almost 3 years
    @Nemo - are you sure about the indexing and iteration? Why not test it (benchmarkdotnet can help here)?
  • 0xF
    0xF almost 3 years
    This 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
    nawfal almost 3 years
    @0xF Fortunately Array.Empty<T>() wheel had not been invented when I wrote this answer :)
  • 0xF
    0xF almost 3 years
    @nawfal Array.Empty<T>() appeared in .NET Framework 4.6, so one year after your answer. Apologies!