7

I have a code that looks like (more or less) :

public void INeedHolidaysNow(double[,]){
     //... Code to take a break from coding and fly to Hawaii
}

double[][] WageLossPerVacationDay = new  double[10][5];

INeedHolidays(WageLossPerVacationDay); // >>throws the Exception in the Title

I found the solution on this post which consists in looping rather thant trying a savage cast

So my question is : WHY ? what happens behind the scenes in the memory allocation that prevents what may seem - at least at first glance, to be a feasible cast ? I mean structurally, both expression seem to be quite identic. What is it that I am missing here ?

EDIT: I have to use "double[ ][ ]" as it is provided by an external library.

Community
  • 1
  • 1
Mehdi LAMRANI
  • 11,289
  • 14
  • 88
  • 130

4 Answers4

11

One is a jagged array, the other is one big block.

double[][] is an array that contains arrays of double. Its form is not necessarily rectangular. In c terms its similar to a double**

double[,] is just one big block of memory, and it is always rectangular. In c terms it's just a double* where you use myArray[x+y*width] to access an element.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
6

One is called multidimensional array (double[*,*]) and other is called jagged array (double[][]).

Here is a good discussion over differences between them.

What is differences between Multidimensional array and Array of Arrays in C#?

Community
  • 1
  • 1
decyclone
  • 30,394
  • 6
  • 63
  • 80
2

Quite simply, [,] arrays (2D arrays) and [][] arrays (jagged arrays) aren't the same.

A [,] array can be visually represented by a rectangle (hence it's also known as a rectangular array), while a [][] array is a 1D array that contains other 1D arrays.

It wouldn't make much sense to be able to cast one to the other.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

You should define your double array like this:

double[,] WageLossPerVacationDay  = new double[3, 5];

Then it should work!

hth

Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54