Home > Back-end >  Make an array completely empty
Make an array completely empty

Time:01-19

I want to make this array completely empty.

string[] strNumbers = new string[3] { "1", "2", "3" };

So I want it to be this

strNumbers = {}

Using the function

 Array.Clear();

CodePudding user response:

why don't use this

 strNumbers = new string[3] ;

CodePudding user response:

Array.Clear will set elements of array to the default values (null for string) but will keep the size of array. Just new up the array:

strNumbers = new string[0];

Or even better:

strNumbers = Array.Empty<string>();

CodePudding user response:

Unclear what you are asking.

  1. Create a new array with no elements

    string[] strNumbers = new string[0];
    

    or

    string[] strNumbers = Array.Empty<string>();
    

    strNumbers.Length will be zero

  2. Create a new array but leave contents empty

    string[] strNumbers = new string[3];
    

    contents will be three null values

  3. Take an existing array and remove all the elements

    Arrays in C# are of fixed size. You cannot add or remove elements from arrays. If you need variable size arrays, use List<string> or some other collection type.

  4. Take an existing array and set the contents to their default values

    for(int i=0; i<strNumbers.Length; i  )
    {
        strNumbers[i] = default(string);
    }
    

    or

    Array.Clear(strNumbers, 0, strNumbers.Length);
    
  • Related