Coder Perfect

How can I use a single value to populate/instantiate a C# array?

Problem

I’m aware that in C#, instantiated arrays of value types are automatically supplied with the type’s default value (e.g. false for bool, 0 for int, etc.).

Is there a way to auto-populate an array with a non-default seed value? Either at the time of construction or later with a built-in method (like Java’s Arrays.fill())? Let’s say I wanted a boolean array that defaulted to true rather than false. Is there a built-in mechanism to do this, or do you have to use a for loop to iterate through the array?

 // Example pseudo-code:
 bool[] abValues = new[1000000];
 Array.Populate(abValues, true);

 // Currently how I'm handling this:
 bool[] abValues = new[1000000];
 for (int i = 0; i < 1000000; i++)
 {
     abValues[i] = true;
 }

It seems inefficient to have to iterate through the array and “reset” each entry to true. Is there a way to get around it? Perhaps by flipping all of the values?

After typing this question and thinking about it, I believe the default values are simply a product of how C# handles the memory allocation of these objects behind the scenes, therefore I doubt it’s doable. However, I’d like to be certain!

Asked by patjbs

Solution #1

Enumerable.Repeat(true, 1000000).ToArray();

Answered by Rony

Solution #2

I’m not aware of a framework function for this, but you could develop a simple helper to do it.

public static void Populate<T>(this T[] arr, T value ) {
  for ( int i = 0; i < arr.Length;i++ ) {
    arr[i] = value;
  }
}

Answered by JaredPar

Solution #3

Make a new array with 1,000 true values as follows:

var items = Enumerable.Repeat<bool>(true, 1000).ToArray();  // Or ToList(), etc.

Integer sequences can be generated in the same way:

var items = Enumerable.Range(0, 1000).ToArray();  // 0..999

Answered by bytebender

Solution #4

You can make use of Array. Fill in the following fields:.NET Core 2.0+ and.NET Standard 2.1+.

Answered by juFo

Solution #5

For large arrays or arrays that will be variable sized you should probably use:

Enumerable.Repeat(true, 1000000).ToArray();

You can use the collection initialization syntax in C# 3 for tiny arrays:

bool[] vals = new bool[]{ false, false, false, false, false, false, false };

The advantage of using the collection initialization syntax is that you don’t have to use the same value in each slot and may instead use expressions or functions to do so. In addition, I believe you have avoided the cost of setting the array slot to the default value. As an example:

bool[] vals = new bool[]{ false, true, false, !(a ||b) && c, SomeBoolMethod() };

Answered by LBushkin

Post is based on https://stackoverflow.com/questions/1014005/how-to-populate-instantiate-a-c-sharp-array-with-a-single-value