Until recently, if I had to reset the array, I used the method of the form

private Vector3[] coord; coord = new Vector3[15]; coord = null; 

And everything worked. But recently stumbled upon

 Array.Clear - метод (Array, Int32, Int32) 

Those. It turns out that all this time my arrays have not been reset. Or is it just some kind of syntactic sugar?

    1 answer 1

    These are completely two different actions. Let us examine each case:

    Here we create a link to the future array:

     private Vector3[] coord; 

    Here we initialize this link with an array of 15 elements, where each of the 15 elements is null :

     coord = new Vector3[15]; 

    Here we make the link empty (return to the state as after the first line), while the array of 15 elements created in the second line will be lost, it will be deleted by the garbage collector in the future (if you no longer make references to it):

     coord = null; 

    Now the second case with Array.Clear :

    This method passes through the existing array and resets each of its elements, i.e. performs the operation coord[i] = null for each i

    That is, the difference is that either we reset the entire link, or reset the elements.

    Let's use a simple example of an array of strings:

     String[] strings; //имеем ссылку `strings - null` strings = new String[3]; strings[0] = "Вася"; strings[1] = "Петя"; strings[2] = "Миша"; strings = null; //По факту наш массив с Васей, Петей и Мишей ещё жив, до запуска сборщика мусора, но обратиться к нему мы уже не можем, так как ссылка на объект потеряна 

    If you do this:

     String[] strings; //имеем ссылку `strings - null` strings = new String[3]; strings[0] = "Вася"; strings[1] = "Петя"; strings[2] = "Миша"; String[] vasyaPetyaMisha = strings; //Создали ещё одну ссылку на массив strings = null;//Вася Петя Миша все ещё живы по ссылке vasyaPetyaMisha 

    With Arrays.Clear :

     String[] strings; //имеем ссылку `strings - null` strings = new String[3]; strings[0] = "Вася"; strings[1] = "Петя"; strings[2] = "Миша"; Array.Clear(strings, 0, 3); //strings[0] = null, //strings[1] = null, //strings[2] = null; //Васи Пети Миши больше нет 

    What's better? Depends on the task. In the first case, you do not clear the array, but forget about it (or re-create it, unless of course in the future you will again initialize the coords ). That is, you will be allocated memory for this array in some other place. In the second case, the allocated memory area will be reused.