abenci
abenci

Reputation: 8651

How do I quicky fill an array with a specific value?

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

Thanks.

Upvotes: 15

Views: 12055

Answers (5)

Michael Rauch
Michael Rauch

Reputation: 1

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)

Upvotes: 0

jo_Veera
jo_Veera

Reputation: 303

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

Array.Fill(test,int.MinValue)

Upvotes: 1

moberme
moberme

Reputation: 689

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]);

Upvotes: 0

apros
apros

Reputation: 2878

The other way is:

int[] arr =  Enumerable.Repeat(-1, 10).ToArray();
Console.WriteLine(string.Join(",",arr));

Upvotes: 20

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

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);

Upvotes: 3

Related Questions