Solutions For Fill The Array With One Value In C#

Solutions For Fill The Array With One Value Banner Image

Introduction

There are three ways in C# that we can approach filling the whole array with a single value, with Enumerable Repeat, Array Fill, and a for loop approach. Each of these will have pros and cons. Including how wide the support for each of these methods is. Also, discussion about how fast each of these methods is and how they compare to each other.

This is useful because if you have a large array, then you don't want to set this manually through the array initializer, it is better to have an automated process. This can be just in just one line of code or just a few lines.

I'll also briefly talk about how readable and concise the code is. Below is a summary table with all the relevant parameters we will look at.

Video With Examples

Summary Table

Analysis TypeEnumerable RepeatArray FillFor Loop
.NET Version Available>= .NET 3.5>= .NET Core 2.0 or .NET Standard 2.1All
PerformanceO(N)O(N)O(N)
Lines Of Code125
Speed5922ms6374ms9941ms

Fill The Array With One Value Using The Enumerable Repeat Method

Enumerable Repeat Flow Chart

Enumerable has a static method called repeat. This means that you don't need to create a new instance of the class but can call it directly on the class name itself. Then there's the method itself called Repeat. It just comes in one flavor with no overloads. It takes in the value which can be any object including C# reference and value types and classes that you can create. This object and its value will be repeated several times you give in the next parameter which will be the size of the output array. This method returns an IEnumerable object which is why we need to apply the LINQ ToArray method to convert it from IEnumerable to Array type.

Enumerable Repeat has been around for some time since .NET 3.5 so it would find wide compatibility and you shouldn't be as concerned that it is not available.

Performance, while this function would still iterate several times needs to fill the array so that is why it is O(N) because it will need to create the number of objects that it is asked to generate.

It's great that it is only one line of code. This is what we would expect for a built-in function in C#. The name itself is also decent as it will repeat the object and number of times specified which is an indication of what it is doing.

Enumerable Repeat Code Example

Enumerable Repeat Syntax Image

This example, takes in various different types into a method that calls the Enumerable Repeat method. This shows how the repeat method can take in any type and how each type can be configured and passed to the method. Then the values are printed. Below is the example code and sample output.

int arraySize = 20;
string[] stringArray = FillArrayWithOneValue<string>(arraySize, "The Grand Canyon");//Fill array
int[] intArray = FillArrayWithOneValue<int>(arraySize , 3);//Fill array
double[] doubleArray = FillArrayWithOneValue<double>(arraySize, 32.00);//Fill array
float[] floatArray = FillArrayWithOneValue<float>(arraySize, 39f);//Fill array
bool[] boolArray = FillArrayWithOneValue<bool>(arraySize, false);//Fill array

PrintArray<string>(stringArray);
PrintArray<int>(intArray);
PrintArray<double>(doubleArray);
PrintArray<float>(floatArray);
PrintArray<bool>(boolArray);

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] filledArray = Enumerable.Repeat<T>(value, arraySize).ToArray();//Enumerable Repeat will generate an IEumerable with the value and the size then convert it to an array
    return filledArray;
}

void PrintArray<T>(T[] array)
{
    int index = 0;
    foreach (T item in array)//Loop through each item in the array
    {
        Console.WriteLine($"[{index++}] = {item}");//Print array item to the screen
    }
    Console.WriteLine();
    Console.WriteLine();
}
Code Output
stringintdoublefloatbool
[0] = The Grand Canyon[0] = 3[0] = 32[0] = 39[0] = False
[1] = The Grand Canyon[1] = 3[1] = 32[1] = 39[1] = False
[2] = The Grand Canyon[2] = 3[2] = 32[2] = 39[2] = False
[3] = The Grand Canyon[3] = 3[3] = 32[3] = 39[3] = False
...............
[18] = The Grand Canyon[18] = 3[18] = 32[18] = 39[18] = False
[19] = The Grand Canyon[19] = 3[19] = 32[19] = 39[19] = False

This shows how each type was correctly output the number of times that was asked.

Fill The Array With One Value Using The Array Fill Method

Array Fill Flow Chart

The Array class also provides a static method that can be called by creating a variable with a typed array. This helps make the method compact which is down to two lines of code. To use this method is a two-step process. You'll need to create an array of the size that you want and the array that you want to be filled with the one value. Then pass that array to the Array Fill method. That is the first parameter in Array Fill. The next parameter is the value that you want to be repeated in the entire array. How this is different from Enumerable Repeat is that in Array Fill you'll have to create an array first and pass it to the function. While Enumerable Repeat generates an array itself.

Note that there is an overload to this method that allows you to pass the start index. Which the point onward to populate the value. So you could partially fill the array with one value and partially fill the other part with another value. So you have another option. with Array Fill.

This again is helpful in that you won't have to manually add this repeated value in an array initializer. Because it could take a long and unnecessary amount of time if the array is large.

This method is first available in the .NET Core 2.1 and .NET Standard 2.1 so it is more recent and so you'll need to check your .NET version to see if this method is supported.

Internally this method loops through the array elements and assigned a new value to each element of the array so the performance is O(n) because every element iterated over.

Array Fill Method Code Example

Array Fill Syntax Image

In this method wrapper, it still takes in array size and the value to be duplicated in the array. Once the array is created with the right size then we can pass the array and the value to the Array Fill function. Array Fill doesn't return anything but fills the array that was passed to it.

int arraySize = 20;
string[] stringArray = FillArrayWithOneValue<string>(arraySize, "The Great Barrier Reef");//Fill array
int[] intArray = FillArrayWithOneValue<int>(arraySize, 25);//Fill array
double[] doubleArray = FillArrayWithOneValue<double>(arraySize, 99.00);//Fill array
float[] floatArray = FillArrayWithOneValue<float>(arraySize, 70f);//Fill array
bool[] boolArray = FillArrayWithOneValue<bool>(arraySize, true);//Fill array

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] newArray = new T[arraySize];//Create new array to be filled
    Array.Fill(newArray, value);//Fill each element of the array with the value
    return newArray;
}
Code Output
stringintdoublefloatbool
[0] = The Great Barrier Reef[0] = 25[0] = 99[0] = 39[0] = True
[1] = The Great Barrier Reef[1] = 25[1] = 99[1] = 39[1] = True
[2] = The Great Barrier Reef[2] = 25[2] = 99[2] = 39[2] = True
[3] = The Great Barrier Reef[3] = 25[3] = 99[3] = 39[3] = True
...............
[18] = The Great Barrier Reef[18] = 25[18] = 99[18] = 39[18] = True
[19] = The Great Barrier Reef[19] = 25[19] = 99[19] = 39[19] = True

Fill The Array With One Value Using For Loop Method

For Loop Flow Chart

We can write out our method to fill the array with a value. I started by initializing the array of a certain size then looped through this array and used the array indexer to assign the value to all the entries. We can reuse this in our code in different places or modify it however we see fit.

Since we can write this ourselves it doesn't have any limitation on which .NET version we use.

For the performance, we have to iterate through all the indexes of the array so that makes it O(N).

For Loop Method Code Example

int arraySize = 20;
string[] stringArray = FillArrayWithOneValue<string>(arraySize, "Mount Everest");//Fill array
int[] intArray = FillArrayWithOneValue<int>(arraySize, 2975);//Fill array
double[] doubleArray = FillArrayWithOneValue<double>(arraySize,8929.00);//Fill array
float[] floatArray = FillArrayWithOneValue<float>(arraySize, 780f);//Fill array
bool[] boolArray = FillArrayWithOneValue<bool>(arraySize, false);//Fill array

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] newArray = new T[arraySize];//Create new array to be filled
    for (int i = 0; i < arraySize; i++)//Loop Through the array
    {
        newArray[i] = value;//assign the value to the array element
    }
    return newArray;
}
Code Output
stringintdoublefloatbool
[0] = Mount Everest[0] = 2975[0] = 8929[0] = 780[0] = False
[1] = Mount Everest[1] = 2975[1] = 8929[1] = 780[1] = False
[2] = Mount Everest[2] = 2975[2] = 8929[2] = 780[2] = False
[3] = Mount Everest[3] = 2975[3] = 8929[3] = 780[3] = False
...............
[18] = Mount Everest[18] = 2975[18] = 8929[18] = 780[18] = False
[19] = Mount Everest[19] = 2975[19] = 8929[19] = 780[19] = False

Speed Test

This will be a speed test to generate 5 arrays of different types each holding 10 million entries. There will be ten 10 tests. Each test will have 100 function call loops of the test method where each test method will have to generate.

Test Parameters
Test ParametersTotal
Tests10
Function Calls Per Test100
Objects Per Function Call10 Million

Enumerable Repeat Speed Test Code

int numberOfTests = 10;//Number of tests 
int numberOfFunctionCalls = 100;//Number of function calls made per test
int numberOfObjectsToCreate = 10000000;//Number test objects
string testName = "Enumerable Repeat";//Test name to print to average
void TestMethod()
{
    string[] stringArray = FillArrayWithOneValue<string>(numberOfObjectsToCreate, "The Amazon Rainforest");//Fill array
    int[] intArray = FillArrayWithOneValue<int>(numberOfObjectsToCreate, 649);//Fill array
    double[] doubleArray = FillArrayWithOneValue<double>(numberOfObjectsToCreate, 3282.00);//Fill array
    float[] floatArray = FillArrayWithOneValue<float>(numberOfObjectsToCreate, 23809f);//Fill array
    bool[] boolArray = FillArrayWithOneValue<bool>(numberOfObjectsToCreate, true);//Fill array
}

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] filledArray = Enumerable.Repeat<T>(value, arraySize).ToArray();//Enumerable Repeat will generate an IEumerable with the value and the size then convert it to an array
    return filledArray;
}

Array Fill Speed Test Code

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] newArray = new T[arraySize];//Create new array to be filled
    Array.Fill(newArray, value);//Fill each element of the array with the value
    return newArray;
}

For Loop Speed Test Code

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] newArray = new T[arraySize];//Create new array to be filled
    for (int i = 0; i < arraySize; i++)//Loop Through the array
    {
        newArray[i] = value;//assign the value to the array element
    }
    return newArray;
}

Enumerable Repeat Code Output
Test 1: 0m 6s 433ms
Test 2: 0m 5s 867ms
Test 3: 0m 5s 888ms
Test 4: 0m 5s 858ms
Test 5: 0m 5s 851ms
Test 6: 0m 5s 828ms
Test 7: 0m 5s 841ms
Test 8: 0m 5s 838ms
Test 9: 0m 5s 905ms
Test 10: 0m 5s 901ms
Enumerable Repeat Average Speed:5922ms, In 10 Tests
Array Fill Code Output
Test 1: 0m 7s 479ms
Test 2: 0m 7s 74ms
Test 3: 0m 6s 906ms
Test 4: 0m 6s 140ms
Test 5: 0m 5s 906ms
Test 6: 0m 5s 927ms
Test 7: 0m 6s 12ms
Test 8: 0m 6s 134ms
Test 9: 0m 6s 227ms
Test 10: 0m 5s 933ms
Array Fill Average Speed:6374ms, In 10 Tests
For Loop Code Output
Test 1: 0m 10s 267ms
Test 2: 0m 9s 923ms
Test 3: 0m 9s 937ms
Test 4: 0m 9s 881ms
Test 5: 0m 9s 917ms
Test 6: 0m 9s 887ms
Test 7: 0m 9s 888ms
Test 8: 0m 9s 914ms
Test 9: 0m 9s 930ms
Test 10: 0m 9s 863ms
For Loop Average Speed:9941ms, In 10 Tests
Full Enumerable Repeat Test Code
using System.Diagnostics;

int numberOfTests = 10;//Number of tests 
int numberOfFunctionCalls = 100;//Number of function calls made per test
int numberOfObjectsToCreate = 10000000;//Number test objects
string testName = "Enumerable Repeat";//Test name to print to average
void TestMethod()
{
    string[] stringArray = FillArrayWithOneValue<string>(numberOfObjectsToCreate, "The Amazon Rainforest");//Fill array
    int[] intArray = FillArrayWithOneValue<int>(numberOfObjectsToCreate, 649);//Fill array
    double[] doubleArray = FillArrayWithOneValue<double>(numberOfObjectsToCreate, 3282.00);//Fill array
    float[] floatArray = FillArrayWithOneValue<float>(numberOfObjectsToCreate, 23809f);//Fill array
    bool[] boolArray = FillArrayWithOneValue<bool>(numberOfObjectsToCreate, true);//Fill array
}

T[] FillArrayWithOneValue<T>(int arraySize, T value)
{
    T[] filledArray = Enumerable.Repeat<T>(value, arraySize).ToArray();//Enumerable Repeat will generate an IEumerable with the value and the size then convert it to an array
    return filledArray;
}

List<double> testSpeedList = new List<double>();
for (int testIndex = 0; testIndex < numberOfTests; testIndex++)
{
    testSpeedList.Add(StartTest(testIndex));
}
Console.WriteLine($"{testName} Average Speed:{Math.Round(testSpeedList.Average())}ms, In {numberOfTests} Tests");

double StartTest(int testIndex)
{
    Stopwatch stopwatch = new Stopwatch();
    for (int i = 0; i < numberOfFunctionCalls; i++)
    {
        stopwatch.Start();//Start the Stopwatch timer
        TestMethod();//
        stopwatch.Stop();//Stop the Stopwatch timer
    }
    stopwatch.Stop();//Stop the Stopwatch timer
    Console.WriteLine($"Test {testIndex + 1}: {stopwatch.Elapsed.Minutes}m {stopwatch.Elapsed.Seconds}s {stopwatch.Elapsed.Milliseconds}ms");
    return stopwatch.Elapsed.TotalMilliseconds;
}

Conclusion

Enumerable Repeat is the best method for filling an array with one value. It is the fastest method and has wide support in the framework.

Array Fill is the second fastest method, but its support is more limited. There is some flexibility to do a partial fill of the array so it will depend on your use case to consider.

For loop, method turned out to be the slowest method and it takes up more lines of code so it would be better to use the built-in methods for this use case.

Know any other solution to fill an entire array with one value? Let me know in the comments below.

Get Latest Updates