Home >Backend Development >C++ >How to Efficiently Initialize C# Arrays with Non-Default Values?

How to Efficiently Initialize C# Arrays with Non-Default Values?

DDD
DDDOriginal
2025-01-04 14:04:39331browse

How to Efficiently Initialize C# Arrays with Non-Default Values?

Populating Array Elements with Non-Default Values in C#

C# arrays of value types are automatically initialized with the type's default value. While this behavior is convenient for initializing arrays with default values, it may be desirable to initialize elements with non-default values.

One approach, mentioned in the provided code, involves iterating through the array and setting each element individually. This method can be inefficient for large arrays. Another approach utilizes the Enumerable.Repeat() method combined with ToArray():

bool[] abValues = Enumerable.Repeat(true, 1000000).ToArray();

This code initializes each element of the abValues array with the value true, overcoming the issue of default initialization. The Enumerable.Repeat() method generates an infinite sequence of the specified value, and ToArray() creates an array based on the sequence.

This method is more efficient than manual iteration, especially for large arrays, as it leverages the inherent properties of Enumerable.Repeat(), which is optimized for creating repeated sequences.

The above is the detailed content of How to Efficiently Initialize C# Arrays with Non-Default Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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