Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Initialization ways

Tags:

c#

linq

I know that we can initialise an array in one of two ways:

  1. Loop (No Memory reflection issues)
  2. Enumerable.Repeat (Probably causes memory issues? Link: Enumerable.Repeat has some memory issues?)

I have two questions:

  1. 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.

  2. What are the other array initialisation methods without any memory issues?

like image 538
Nikhil Agrawal Avatar asked Dec 20 '22 23:12

Nikhil Agrawal


2 Answers

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();
like image 143
Jon Avatar answered Dec 23 '22 14:12

Jon


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;
}
like image 39
Pavel Krymets Avatar answered Dec 23 '22 12:12

Pavel Krymets