How can I quickly up-cast object[,] into double[,]?

John Alexiou picture John Alexiou · Feb 22, 2011 · Viewed 10.7k times · Source

I using Microsoft.Office.Interop.Excel I get returned a 2D array of type object[,] which contains double for elements. Note that the index lower bound is 1 instead of the default 0, but I can deal with that easily.

How can nicely convert the array into double[,] using .NET 3.5. (by nicely I mean concise, or compact).

Note that

double[] values_2 = values.Cast<double>().ToArray();

does work, but it flattens by array into a 1D structure.

Answer

Marlon picture Marlon · Feb 22, 2011
object[,] src = new object[2, 3];

// Initialize src with test doubles.
src[0, 0] = 1.0;
src[0, 1] = 2.0;
src[0, 2] = 3.0;
src[1, 0] = 4.0;
src[1, 1] = 5.0;
src[1, 2] = 6.0;

double[,] dst = new double[src.GetLength(0), src.GetLength(1)];
Array.Copy(src, dst, src.Length);