Home >Backend Development >C++ >How to Efficiently Initialize a C# Array with a Custom Value?
Question:
In C#, arrays of value types are automatically initialized with the default value of their type. However, what if you want to populate the array with a non-default value? Is there a built-in method or more efficient approach than iterating through the array and setting each element manually?
Answer:
Yes, there is a built-in method to accomplish this using the Enumerable.Repeat() method.
bool[] abValues = Enumerable.Repeat(true, 1000000).ToArray();
The Enumerable.Repeat() method takes a value and a count as parameters and generates a sequence of that value repeated the specified number of times. By combining the result with the ToArray() method, it initializes an array of the desired size, with every element set to the specified value.
This approach is more efficient than iterating through the array manually, especially for large arrays. It leverages the underlying memory management capabilities of C# to initialize the array directly with the desired values, avoiding the need for additional loops and assignments.
The above is the detailed content of How to Efficiently Initialize a C# Array with a Custom Value?. For more information, please follow other related articles on the PHP Chinese website!