Search code examples
c#vb.netoffice-interop

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


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.


Solution

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