S
S
Sergey Panov2018-06-07 18:54:40
C++ / C#
Sergey Panov, 2018-06-07 18:54:40

How to completely clear an array?

Good evening friends.
There is an array

public int[] checkAddDel;

checkAddDel = new int[Word.Length]

As the script executes, the array is filled.
I need to eventually reset it to 0 elements. How to do it, tell me please?
The List list is no longer an option, a lot of rewriting)

Answer the question

In order to leave comments, you need to log in

6 answer(s)
E
eRKa, 2018-06-07
@select8

checkAddDel = new int[0]
An array always has a predefined length, which does not change, you can only create a new one with the desired size.

S
Sumor, 2018-06-07
@Sumor

After use, you can do: or And the previously filled array will be destroyed by the garbage collector.

T
Tom Nolane, 2018-06-07
@tomnolane

use static Array class with Resize method from msdn itself

var myArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Array.Resize(ref myArray, 0);

A
Alexey Pavlov, 2018-06-08
@lexxpavlov

It might be better to take a list instead of an array:List<int>

public List<int> checkAddDel;

checkAddDel = new List<int>(Word.Length); // предварительно указывать размер не обязательно, 
                                          // но если известно заранее, то лучше указать

Console.WriteLine(checkAddDel.Count); // 0
for (var i = 0; i < Word.Length; i++)
{
    checkAddDel.Add((i + 1) * 10);
}
Console.WriteLine(checkAddDel.Count); // размер теперь стал равным Word.Length

// используем список
DoWork(checkAddDel);

checkAddDel.Clear(); // теперь стал пустым
Console.WriteLine(checkAddDel.Count); // 0

#
#, 2018-06-08
@mindtester

The List list is no longer an option, a lot of rewriting)
Actually, it's the only reasonable option. and if you master the features of VS refactoring, then it’s unlikely that you will rewrite too much

T
ToKoMoK, 2020-04-23
@ToKoMoK

var_myArray = Array.Empty();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question