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
Release: 2024-12-31 14:02:13
Original
973 people have browsed it

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

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!

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