Unable To Cast object type 'System.String[*]' to type 'System.String[]'

Manuel Espino picture Manuel Espino · Sep 14, 2012 · Viewed 7.2k times · Source

Hi everyone i had a issue with a code in C# .NET, I'm using a DLL for connect to OPC Servers the DLL that was used in a VB.NET project and works with no problem at all.

I'm trying to show a list of available Servers in a ListBox, the code used in VB.NET (and works) is this one:

Dim AllOPCServers As Object
AllOPCServers = AnOPCServer.GetOPCServers

' Load the list returned into the List box for user selection
Dim i As Short
For i = LBound(AllOPCServers) To UBound(AllOPCServers)
    AvailableOPCServerList.Items.Add(AllOPCServers(i))
Next i

and i wrote this to use in the C# application

try
{
    var _listOPCServer = _OPCServer.GetOPCServers();
    foreach(var i in _listOPCServer)
    {
        string serverName = (string)i;
        listServers.Items.Add(serverName);
    }             
}
catch (Exception exc)
{
    lstMsg.Items.Add(DateTime.Now + " Error al Obtener Lista de OPC's: " + exc.Message);
}

On Debug mode on Local tab shows this:

_listOPCServer | {string[1..2]} | dynamic {string[]} |

[1]        |  "Server01"    | string  
[2]        |  "Server02"    | string

UPDATE:

I get the error in line "foreach(var i in _listOPCServer)"

Unable To Cast object type 'System.String[*]' to type 'System.String[]'

That is the actually error.

I'm sure that I'm doing something wrong, can someone help me?

Answer

Manuel Espino picture Manuel Espino · Sep 14, 2012

Ok i found a way to work this out and it's only a mod of your advices

 Array _listOPCServer = (Array)(object)_OPCServer.GetOPCServers();               

            foreach(object i in _listOPCServer)
            {
                string serverName = (string)i;
                listServers.Items.Add(serverName);
            }             

I only added (object) in the declaration and works fine, now i can show the list of servers just the way i wanted it

or also do this

Array _listOPCServer = (Array)(object)_OPCServer.GetOPCServers();               

            foreach(object i in _listOPCServer)
            {
                listServers.Items.Add(i);
            }

Again, thanks a lot for your help and time!