I know that we can initialise an array in one of two ways:
Enumerable.Repeat
(Probably causes memory issues? Link: Enumerable.Repeat has some memory issues?)I have two questions:
Can we initialise an array using Array.ForEach
in this manner?
double[][] myarr = new double[13][];
Array.ForEach(myarr, *enter_code_here*);
I tried replacing enter_code_here
with:
s => s = new double[2];
but it does not initialise myarr
.
What are the other array initialisation methods without any memory issues?
You can use Enumerable.Repeat
just fine to initialize any array. The only thing you need to be careful of is that if the array element is of a reference type there are two ways to go about it:
// #1: THIS ARRAY CONTAINS 10 REFERENCES TO THE SAME OBJECT
var myarr = Enumerable.Repeat(new object(), 10).ToArray();
// #2: THIS ARRAY CONTAINS REFERENCES TO 10 DIFFERENT OBJECTS
var myarr = Enumerable.Range(0, 10).Select(i => new object()).ToArray();
// #3: SAME RESULT AS #2 BUT WITH Enumerable.Repeat
var myarr = Enumerable.Repeat(0, 10).Select(i => new object()).ToArray();
A1: No, you can't. Foreach just executes method with element as parameter but don't modify elements.
A2: You can use the folowing method to resolve the issue
static T[][] CreateArray<T>(int rows, int cols)
{
T[][] array = new T[rows][];
for (int i = 0; i < array.GetLength(0); i++)
array[i] = new T[cols];
return array;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With