Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

Array Initialization ways

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?

Upvotes: 4

Views: 2445

Answers (3)

user2883718
user2883718

Reputation: 1

This is how I created a 256 row x 2 column array and initialized all values to -1.

int[][] myArr = Enumerable.Range(0, 256).Select(i => new int[2] {-1, -1}).ToArray();

Upvotes: 0

Jon
Jon

Reputation: 437336

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();

Upvotes: 8

Pavel Krymets
Pavel Krymets

Reputation: 6293

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;
}

Upvotes: 3

Related Questions