Tuesday, September 21, 2004

Casting arrays returned by COM methods in .NET C#

Keywords: VB6 multi-dimensional array casting .NET C# Interop

Summary of the problem: some method defined in a COM component returns 2-dimensional arrays, but is declared as Variant:

Variant getArray()

In .NET / C#, this translates to object

object getArray()

My problem was with casting this as a string array. I tried the following:

string[,] myarray = (string[,])getArray());
Console.Write(myarray[0,0]);


This throws a "specified cast is not valid" exception. In retrospect, the solution is very obvious, but I struggled for a while to find it:

System.Array myarray = (System.Array)getArray();
Console.Write(myarray.GetValue(0, 0).ToString());

Incidentally, the following does not work (also invalid cast exception):

string[] record = new string[1];
record[0] = myarray.GetValue(0, 0).ToString();


but this does:

string temp;
string[] record = new string[1];
temp = myarray.GetValue(0, 0).ToString();
record[0] = temp;

Does anyone know why?

1 Comments:

Blogger Jon Schneider said...

I was also struggling with the issue of trying to cast a multidimensional array returned from a COM call into a specific type. I turned up your post on a Google search for ["Specified cast is not valid" "System.Array" multidimensional].

This should save me a lot of time tracking down the problem. Thanks, Andrew! :-)

11:54 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home