[c#] 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?

This question is related to c# arrays initialization

The answer is


string[] a = new string[0];

or short notation:

string[] a = { };

The preferred way now is:

var a = Array.Empty<string>();

I have written a short regular expression that you can use in Visual Studio if you want to replace zero-length allocations e.g. new string[0]. Use Find (search) in Visual Studio with Regular Expression option turned on:

new[ ][a-zA-Z0-9]+\[0\]

Now Find All or F3 (Find Next) and replace all with Array.Empty<…>() !


Try this:

string[] a = new string[] { };

I had tried:

string[] sample = new string[0];

But I could only insert one string into it, and then I got an exceptionOutOfBound error, so I just simply put a size for it, like

string[] sample = new string[100];

Or another way that work for me:

List<string> sample = new List<string>();

Assigning Value for list:

sample.Add(your input);

Here is a real world example. In this it is necessary to initialize the array foundFiles first to zero length.

(As emphasized in other answers: This initializes not an element and especially not an element with index zero because that would mean the array had length 1. The array has zero length after this line!).

If the part = string[0] is omitted, there is a compiler error!

This is because of the catch block without rethrow. The C# compiler recognizes the code path, that the function Directory.GetFiles() can throw an Exception, so that the array could be uninitialized.

Before anyone says, not rethrowing the exception would be bad error handling: This is not true. Error handling has to fit the requirements.

In this case it is assumed that the program should continue in case of a directory which cannot be read, and not break- the best example is a function traversing through a directory structure. Here the error handling is just logging it. Of course this could be done better, e.g. collecting all directories with failed GetFiles(Dir) calls in a list, but this will lead too far here.

It is enough to state that avoiding throw is a valid scenario, and so the array has to be initialized to length zero. It would be enough to do this in the catch block, but this would be bad style.

The call to GetFiles(Dir) resizes the array.

string[] foundFiles= new string[0];
string dir = @"c:\";
try
{
    foundFiles = Directory.GetFiles(dir);  // Remark; Array is resized from length zero
}
// Please add appropriate Exception handling yourself
catch (IOException)
{
  Console.WriteLine("Log: Warning! IOException while reading directory: " + dir);
  // throw; // This would throw Exception to caller and avoid compiler error
}

foreach (string filename in foundFiles)
    Console.WriteLine("Filename: " + filename);

Simple and elegant!

string[] array = {}

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:


You can do:

string[] a = { String.Empty };

Note: OP meant not having to specify a size, not make an array sizeless


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

Combining @nawfal & @Kobi suggestions:

namespace Extensions
{
    /// <summary> Useful in number of places that return an empty byte array to avoid unnecessary memory allocation. </summary>
    public static class Array<T>
    {
        public static readonly T[] Empty = new T[0];
    }
}

Usage example:

Array<string>.Empty

UPDATE 2019-05-14

(credits to @Jaider ty)

Better use .Net API:

public static T[] Empty<T> ();

https://docs.microsoft.com/en-us/dotnet/api/system.array.empty?view=netframework-4.8

Applies to:

.NET Core: 3.0 Preview 5 2.2 2.1 2.0 1.1 1.0

.NET Framework: 4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6

.NET Standard: 2.1 Preview 2.0 1.6 1.5 1.4 1.3

...

HTH


As I know you can't make array without size, but you can use

List<string> l = new List<string>() 

and then l.ToArray().


You can define array size at runtime.

This will allow you to do whatever to dynamically compute the array's size. But, once defined the size is immutable.

Array a = Array.CreateInstance(typeof(string), 5);

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];

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization