Home > Backend Development > C++ > How to Efficiently Initialize a C# Array with a Custom Value?

How to Efficiently Initialize a C# Array with a Custom Value?

Barbara Streisand
Release: 2025-01-04 14:23:43
Original
271 people have browsed it

How to Efficiently Initialize a C# Array with a Custom Value?

Initializing 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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template