aquanat
aquanat

Reputation: 2137

C# declare empty string array

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?

Upvotes: 209

Views: 404749

Answers (11)

Nwafor
Nwafor

Reputation: 184

// zero-element array
var arr0 = System.Array.Empty<string>(); // Recommended: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1825
var arr1 = new string[0];

// 5-Elements array with null values
var arr2 = new string[5];

// 5-Elements array with empty string values
var arr3 = System.Linq.Enumerable.Repeat(string.Empty, 5).ToArray();
var arr4 = System.Linq.Enumerable.Range(0, 5).Select(_ => string.Empty).ToArray();

Upvotes: 0

Martin
Martin

Reputation: 1

could get something like this with: private List list = new List(); string[] dnormlines kist.ToArray();

Upvotes: -2

Brian
Brian

Reputation: 511

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

Upvotes: 49

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

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)

Upvotes: 2

The following should work fine.

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

Upvotes: -5

Atish Kumar Dipongkor
Atish Kumar Dipongkor

Reputation: 10422

Try this

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

Upvotes: 348

CodeCaster
CodeCaster

Reputation: 151594

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

Upvotes: 0

Andrei
Andrei

Reputation: 56688

Your syntax is wrong:

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

or

string[] arr = new string[0];

Upvotes: 78

Rahul
Rahul

Reputation: 5636

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

Upvotes: 0

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

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)

Upvotes: 9

Bharadwaj
Bharadwaj

Reputation: 2553

You can try this

string[] arr = {};

Upvotes: 9

Related Questions