Cool new way to fill array with a value in .NET Core

Can you count how many times you wrote something like:

var prime = new bool[1000];
for ( int i = 0; i < isPrime.Length; i++ )
{
prime[i] = true;
}

view raw
ForArrayFill.cs
hosted with ❤ by GitHub

Or if you fancy LINQ (and can sacrifice a bit of performance)?

var prime = Enumerable.Repeat(true, 1000).ToArray();

If your answer is infinite or more, then check out the new way available in .NET Core 2.0 and newer:

var data = new bool[1000];
Array.Fill(data, true);

view raw
CoreArrayFill.cs
hosted with ❤ by GitHub

Array.Fill brings the best of both worlds – it is more succinct than a for-loop while being more performant than Enumerable.Repeat.

As .NET Core is open source and we like to peek under the hood, we can see the Array.Fill method is basically just a shorthand for plain for loop:

public static void Fill<T>(T[] array, T value)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
for (int i = 0; i < array.Length; i++)
{
array[i] = value;
}
}

It is also worth mentioning that Array.Fill has another overload which lets us specify which range of indices should be filled:

public static void Fill<T> (T[] array, T value, int startIndex, int count);

view raw
ArrayFillOverride.cs
hosted with ❤ by GitHub

Buy me a coffeeBuy me a coffee

1 thought on “Cool new way to fill array with a value in .NET Core”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.