C# declare empty string array

前端 未结 9 569
囚心锁ツ
囚心锁ツ 2020-12-23 12:51

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.<

相关标签:
9条回答
  • 2020-12-23 13:19

    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)

    0 讨论(0)
  • 2020-12-23 13:23

    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();
    
    0 讨论(0)
  • 2020-12-23 13:24

    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];
    
    0 讨论(0)
  • 2020-12-23 13:25

    The following should work fine.

    string[] arr = new string[] {""};
    
    0 讨论(0)
  • 2020-12-23 13:32

    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)

    0 讨论(0)
  • 2020-12-23 13:41

    Your syntax is wrong:

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

    or

    string[] arr = new string[0];
    
    0 讨论(0)
提交回复
热议问题