Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear an array

Tags:

arrays

c#

I have a global variable int[] and I want to clear its data and fill it again in a loop.

How could this possible in C#?

like image 414
LIX Avatar asked Apr 20 '10 08:04

LIX


3 Answers

The static Array.Clear() method "sets a range of elements in the Array to zero, to false, or to Nothing, depending on the element type". If you want to clear your entire array, you could use this method an provide it 0 as start index and myArray.Length as length:

Array.Clear(myArray, 0, myArray.Length);
like image 157
Jørn Schou-Rode Avatar answered Oct 04 '22 02:10

Jørn Schou-Rode


This is not correct answer for your post but you can use this logic according to your need. Here is a code Snippets taken from here

using System;

class ArrayClear
{

   public static void Main()
   {
      int[] integers = { 1, 2, 3, 4, 5 };
      DumpArray ("Before: ", integers);
      Array.Clear (integers, 1, 3);
      DumpArray ("After:  ", integers);
   }

   public static void DumpArray (string title, int[] a)
   {
      Console.Write (title);
      for (int i = 0; i < a.Length; i++ )
      {
         Console.Write("[{0}]: {1, -5}", i, a[i]);
      }
      Console.WriteLine();
   }
}

and output of this is:

Before: [0]: 1    [1]: 2    [2]: 3    [3]: 4    [4]: 5
After:  [0]: 1    [1]: 0    [2]: 0    [3]: 0    [4]: 5
like image 27
MAS1 Avatar answered Oct 04 '22 00:10

MAS1


Why not just create new array and assign it to existing array variable?

x = new int[x.length];
like image 4
Janis Veinbergs Avatar answered Oct 04 '22 01:10

Janis Veinbergs