Initializing an array filled with a repeated non-default value
suggest changeAs we know we can declare an array with default values:
int[] arr = new int[10];
This will create an array of 10 integers with each element of the array having value 0 (the default value of type int).
To create an array initialized with a non-default value, we can use Enumerable.Repeat from the System.Linq Namespace:
- To create a
boolarray of size 10 filled with “true”bool[] booleanArray = Enumerable.Repeat(true, 10).ToArray(); - To create an
intarray of size 5 filled with “100”int[] intArray = Enumerable.Repeat(100, 5).ToArray(); - To create a
stringarray of size 5 filled with “C#”string[] strArray = Enumerable.Repeat("C#", 5).ToArray();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents