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

Visual Studio General .NET Core

4 years ago

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: