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!