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

Can you count how many times you wrote something like:

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

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

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:

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

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 class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">


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