Home >Backend Development >C++ >How Can I Initialize a C# Array with Non-Default Values?

How Can I Initialize a C# Array with Non-Default Values?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-31 14:02:131018browse

How Can I Initialize a C# Array with Non-Default Values?

Creating C# Arrays Initialized with Non-Default Values

When instantiating arrays of value types in C#, they are automatically initialized with the default value for the given data type. This implies false for boolean arrays, 0 for integer arrays, and so forth. Can we bypass this behavior and populate arrays with custom seed values during their creation or later?

During array creation, there is no built-in method to achieve this goal. However, using LINQ, we can leverage the Enumerable.Repeat method, which generates a sequence of specified elements within a given count. Combining this with the ToArray() method, we can initialize an array with a repeated value:

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

This effectively creates a boolean array of length 1000000, with all elements set to true.

The above is the detailed content of How Can I Initialize a C# Array 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