2

I have a COM that reads our VMS system and returns an array for Dynamic type.

In visual studio when I inspect the type it shows:

dynamic {object[]}

so I tried the following:

var lines = myApp.GetScreenLines();
foreach(var line in lines)
{
  //Do something
}

But I keep getting the exception:

Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'.

However, if I inspect lines, it shows just like a normal array and I can even expand it to see the data.

Does anyone know how I can convert this dynamic array data type to a string type?

I have tried the solutions in the duplicate link yet they dont seem to work as they assume I know information about the array. But as its dynamic I dont know anything until runtime, so i cant get the lower or upper bounds of the array.

PS I have no control over what myApp.GetScreenLines(); returns as its a COM API.

EDIT:

The solutions provided in the duplicate do not resolve my issue. I have tried both.

The first one ive tried was:

    Array sourceArray = myWinFormsApp.GetScreenLines();
    if (sourceArray.Rank != 1)
    throw new InvalidOperationException("Expected a single-rank array.");

    object[] newArray2 = new object[sourceArray.Length];
    Array.Copy(sourceArray, sourceArray.GetLowerBound(0),
                       newArray2, 0, sourceArray.Length);

This results in the exception: Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'.

The second one I tried was:

object[] newArray = myWinFormsApp.GetScreenLines().Cast<object>().ToArray();

To which I get the exception: 'System.Array' does not contain a definition for 'Cast'

So I dont consider this question a duplicate, as ive explained I can view the array using the "watch" tool in visual studio, but I cant seem to iterate through it

Festivejelly
  • 670
  • 2
  • 12
  • 30
  • Have you tried using `foreach(dynamic line in lines)`? – Matas Vaitkevicius Jun 19 '14 at 16:05
  • Also none of the solutions in the "duplicate" work either. What is returned from the COM is a dynamic value I dont have control over this. – Festivejelly Jun 23 '14 at 07:55
  • I had the same issue as the OP, that the solutions in the linked "answer" don't work with a dynamic. But find RoadBump's post in the linked answer - that worked for me on a dynamic. You have to double cast it through object to Array. Then it's easy to iterate. – Marty Jan 04 '17 at 12:56

1 Answers1

0

Try using dynamic instead of var

var lines = myApp.GetScreenLines();
foreach(dynamic  line in lines)
{
  //Do something
}
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265