how to clear an array

0 votes
asked Apr 20, 2010 by lix

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#?

5 Answers

0 votes
answered Jan 20, 2010 by pratik-deoghare
  int[] x 
  int[] array_of_new_values

  for(int i = 0 ; i < x.Length && i < array_of_new_values.Length ;i++)
  {
        x[i] = array_of_new_values[i]; // this will give x[i] its new value
  }

Why clear it? Just assign new values.

0 votes
answered Jan 20, 2010 by janis-veinbergs

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

x = new int[x.length];
0 votes
answered Apr 20, 2010 by fabian

Wouldnt it be easier to use a list instead.

public List<int> something = new List<int>();

And then:

something.Add(somevalue);

And to clear:

something.Clear();
0 votes
answered Apr 20, 2010 by mas1

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
0 votes
answered Sep 15, 2017 by rouhollah-ghasempour

For two dimensional arrays, you should do as bellow:

Array.Clear(myArray, 0, myArray.GetLength(0)*myArray.GetLength(1));
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...