Multiple Approaches for Populating C# Arrays with Non-Default Values and Performance Analysis

Nov 20, 2025 · Programming · 11 views · 7.8

Keywords: C# Arrays | Array Population | Default Values | Performance Optimization | Extension Methods

Abstract: This article provides an in-depth exploration of efficient methods for populating C# arrays with non-default values. By analyzing the memory allocation mechanisms of arrays, it详细介绍介绍了三种主要实现方式:使用Enumerable.Repeat方法、自定义扩展方法和Array.Fill方法,并比较了它们的性能特点和适用场景。结合 fundamental knowledge of C# arrays, the article offers complete code examples and best practice recommendations to help developers choose the most suitable array population strategy based on specific requirements.

Array Initialization and Default Value Mechanism

In C#, arrays as reference types follow specific rules for memory allocation and initialization. When creating an array using the new keyword, the system allocates contiguous memory space and sets all elements to the default value of the type. For value types like bool and int, the default values are false and 0 respectively; for reference types, the default value is null. This mechanism stems from C#'s type system and memory management strategy, ensuring arrays are in a predictable state after creation.

However, in practical development, we often need to initialize arrays with specific non-default values. For example, creating a boolean array with 1 million true values instead of the default false. While directly using loops to assign values one by one is feasible, it may seem inefficient when dealing with large-scale data. The following sections introduce several more efficient solutions.

Using the Enumerable.Repeat Method

Enumerable.Repeat is a convenient method provided by LINQ that generates a sequence containing specified repeated values. By calling the ToArray() method, this sequence can be converted into an array. This approach features concise syntax and is suitable for quickly creating small to medium-sized arrays filled with specific values.

// Using Enumerable.Repeat to create a boolean array filled with true
bool[] abValues = Enumerable.Repeat(true, 1000000).ToArray();

The advantage of this method is its concise and readable code, but note that its internal implementation may involve additional memory allocation and sequence conversion, potentially incurring performance overhead for very large arrays.

Implementing Custom Extension Methods

To provide a more flexible and efficient array population solution, we can create a custom extension method. This approach directly manipulates array memory, avoiding unnecessary intermediate conversions, and is particularly suitable for handling large-scale data.

// Defining a generic array population extension method
public static void Populate<T>(this T[] arr, T value)
{
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = value;
    }
}

// Using the extension method to populate an array
bool[] abValues = new bool[1000000];
abValues.Populate(true);

The advantages of this method include:

Array.Fill Method (.NET Core 2.0+)

Starting from .NET Core 2.0 and .NET Standard 2.1, C# provides the built-in Array.Fill method, specifically designed for quickly populating arrays. This is the officially recommended solution with optimal performance.

// Using Array.Fill method to populate an array
bool[] abValues = new bool[1000000];
Array.Fill(abValues, true);

The advantages of the Array.Fill method include:

Performance Comparison and Selection Recommendations

When choosing an array population method, consider performance, code readability, and platform compatibility comprehensively:

For performance-sensitive applications, benchmarking is recommended. Typically, Array.Fill and custom extension methods have significant performance advantages over Enumerable.Repeat when handling large arrays, as they avoid the overhead of sequence conversion.

Practical Application Examples

The following is a complete example demonstrating the application of different methods in actual projects:

using System;
using System.Linq;

public class ArrayPopulationExample
{
    // Custom extension method
    public static void Populate<T>(this T[] arr, T value)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            arr[i] = value;
        }
    }
    
    public static void Main()
    {
        const int size = 1000000;
        
        // Method 1: Using Enumerable.Repeat
        var method1 = Enumerable.Repeat(true, size).ToArray();
        
        // Method 2: Using custom extension method
        var method2 = new bool[size];
        method2.Populate(true);
        
        // Method 3: Using Array.Fill (if available)
        var method3 = new bool[size];
        #if NETCOREAPP2_0_OR_GREATER
        Array.Fill(method3, true);
        #endif
        
        Console.WriteLine($"Array size: {size}");
        Console.WriteLine($"Method 1 population result: {method1[0]}");
        Console.WriteLine($"Method 2 population result: {method2[0]}");
        #if NETCOREAPP2_0_OR_GREATER
        Console.WriteLine($"Method 3 population result: {method3[0]}");
        #endif
    }
}

Summary and Best Practices

When populating C# arrays with non-default values, choose the appropriate method based on specific needs:

  1. For new projects or those upgraded to .NET Core 2.0+, prioritize using the Array.Fill method
  2. For projects requiring backward compatibility, use custom extension methods to provide a unified solution
  3. For small-scale data or rapid development, Enumerable.Repeat offers concise syntax
  4. When handling ultra-large arrays, consider using parallelization or lower-level memory operations for further performance optimization

Understanding the memory allocation mechanisms of arrays and the implementation principles of different population methods helps developers make more informed technical choices in actual projects, writing code that is both efficient and maintainable.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.