Advertisement
Advertisement


C# declare empty string array


Question

I need to declare an empty string array and i'm using this code

string[] arr = new String[0]();

But I get "method name expected" error.

What's wrong?

2018/05/17
1
155
5/17/2018 9:26:44 PM

Accepted Answer

Try this

string[] arr = new string[] {};
269
12/12/2013 9:07:39 AM

Your syntax is wrong:

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

or

string[] arr = new string[0];
2013/05/30

If you are using .NET Framework 4.6 and later, they have some new syntax you can use:

using System;  // To pick up definition of the Array class.

var myArray = Array.Empty<string>();
2020/08/25

You can try this

string[] arr = {};
2013/05/30

Arrays' constructors are different. Here are some ways to make an empty string array:

var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()

(sorry, on mobile)

2013/05/30

Your syntax is invalid.

string[] arr = new string[5];

That will create arr, a referenced array of strings, where all elements of this array are null. (Since strings are reference types)

This array contains the elements from arr[0] to arr[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null.

Single-Dimensional Arrays (C# Programming Guide)

2018/05/23