C# declare empty string array

C#ArraysString

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Try this

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

Solution 2 - C#

Your syntax is wrong:

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

or

string[] arr = new string[0];

Solution 3 - C#

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

Solution 4 - C#

You can try this

string[] arr = {};

Solution 5 - C#

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)

Solution 6 - C#

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)

Solution 7 - C#

Those curly things are sometimes hard to remember, that's why there's excellent documentation:

// Declare a single-dimensional array  
int[] array1 = new int[5];

Solution 8 - C#

If you must create an empty array you can do this:

string[] arr = new string[0];

If you don't know about the size then You may also use List<string> as well like

var valStrings = new List<string>();

// do stuff...

string[] arrStrings = valStrings.ToArray();

Solution 9 - C#

The following should work fine.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaquanatView Question on Stackoverflow
Solution 1 - C#Atish DipongkorView Answer on Stackoverflow
Solution 2 - C#AndreiView Answer on Stackoverflow
Solution 3 - C#BrianView Answer on Stackoverflow
Solution 4 - C#BharadwajView Answer on Stackoverflow
Solution 5 - C#It'sNotALie.View Answer on Stackoverflow
Solution 6 - C#Soner GönülView Answer on Stackoverflow
Solution 7 - C#CodeCasterView Answer on Stackoverflow
Solution 8 - C#RahulView Answer on Stackoverflow
Solution 9 - C#Karthikeyan GunashekerView Answer on Stackoverflow