HOW TO POPULATE AN ARRAY WITH A SINGLE VALUE USING C#?

QuestionsCategory: C#HOW TO POPULATE AN ARRAY WITH A SINGLE VALUE USING C#?
Himanshu SHimanshu S asked 1 year ago

As instantiated arrays of value types in C# are automatically populated with the default value of the type (e.g. false for bool, 0 for int, etc.).
Is there a way to auto-populate an array with other value then default value?
For e.g. I want below array all value (all 100) should populate as “Not Tested”.

var arr = new string[100];
1 Answers
Best Answer
Mahesh DeshmaneMahesh Deshmane answered 1 year ago

Solution1:
Below is simple solution using Repeat

var arr = Enumerable.Repeat("Not Tested", 100).ToArray();

Solution 2:
Below is Extension Method:

public static void Init<T>(this T[] array, T value)
{
if (array == null) return;

for (var i = 0; i < array.Length; i++)
{
  array[i] = value;
}
}

Solution 3:
There is new way available in .NET Core 2.0 Array.Fill

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

Under the hood Array.Fill use above mentioned Extension method.