15

Array.Clear() fills the arrays with the default value (zero for integers), I would like to fill it using -1 for example.

Thanks.

abenci
  • 8,422
  • 19
  • 69
  • 134
  • 3
    This question asks effectively the same thing (since there is nothing specific to C# about it): [How to populate/instantiate a C# array with a single value?](http://stackoverflow.com/q/1014005/145173) – Edward Brey Feb 12 '16 at 14:26
  • Yes, see the above link (especially http://stackoverflow.com/a/19727083/2032514) because the answers here (using `Enumerable.Repeat` and simple `for`) don't qualify as "quick". For byte arrays, see http://stackoverflow.com/a/25808955/2032514 – 0xF Mar 18 '16 at 09:59

5 Answers5

19

The other way is:

int[] arr =  Enumerable.Repeat(-1, 10).ToArray();
Console.WriteLine(string.Join(",",arr));
apros
  • 2,848
  • 3
  • 27
  • 31
  • 1
    This is efficient in terms of the amount of code that must be written. But I believe it results in a simple loop. I don't understand why the `Buffer` class doesn't have a Fill method of some sort. – Jonathan Wood Nov 18 '12 at 19:52
  • 4
    Not only does using `Enumerable.Repeat` require iteration through each element at the .NET level (meaning array boundary checks for each access), `ToArray` doesn't know the size of the `IEnumerable`, so it has to guess as to the array size. That means you'll get array allocations every time `ToArray`'s buffer is exceeded, plus one more allocation at the end for the trim. – Edward Brey Feb 12 '16 at 14:24
3

I am not aware of such a method. You could write one yourself, though:

public static void Init<T>(this T[] array, T value)
{
    for(int i=0; i < array.Length; ++i)
    {
        array[i] = value;
    }
}

You can call it like this:

int[] myArray = new int[5];
myArray.Init(-1);
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

For example the array 'test' is filled with min value, so following is the code :

Array.Fill(test,int.MinValue)
jo_Veera
  • 293
  • 3
  • 12
0

One way to do it without using a method.

int[,] array = new int[,]{{0, -1},{-1, 0}}; Console.WriteLine(array[0, 0]); Console.WriteLine(array[0, 1]);

moberme
  • 669
  • 7
  • 13
0

in VB.NET just make a CompilerExtension and Template

Imports System.Runtime.CompilerServices

<Extension>
Public Sub Fill(Of T)(buffer() As T, value As T)
    For i As Integer = 0 To buffer.Length - 1 : buffer(i) = value : Next
End Sub

you can than use it on any array like this

Public MyByteBuffer(255) as Byte
Public MyDoubleBuffer(20) as Double

MyByteBuffer.Fill(&HFF)
MyDoubleBuffer.Fill(1.0)