Search code examples
c#objectcasting

In my C# project I get an string [,] type object as an output. When I want to print the output to console or file, the output is truncated. Why?


I have the method below, where I am subscribing to an OPC DA server items.

public  void read_OPC_items(string ip)
{
    using (var client = new EasyDAClient())
    {
        client.ItemChanged += func_ItemChanged;                
        client.SubscribeMultipleItems(
            new[] {                           
                    new DAItemGroupArguments(ip, "OPC.IwSCP.1", item_name, 1000, null),
                });                
    }
}

public void func_ItemChanged(object sender, EasyDAItemChangedEventArgs e)
{            
    if (e.Succeeded)
    {           
         Console.WriteLine(e.Vtq); // result of item
         Console.WriteLine(e.Vtq.Value)
    }
}

When I print the result to Console I get something like that:

[6, 14] {{1, 1, 0, UPS battery failure., 45305.2620848611, ...}, {1, 1, 0, UPS battery failure., 45304.9276650694, ...}...} System.Object[,]

From the printed lines I understand that the object e.Vtq is a 2D Array. The result is coming just partly correct. Just two rows and 5 columns of the array are displayed correct. As you see the rest of the 2-D array are truncated with "...". How can I print the complete result without being truncated?

Additionally: How can I acces to the elements of the 2D object with index?

When I try something like below it doesn't work. I get: Error CS0021 Cannot apply indexing with [] to an expression of type

string element_of_2darray = e.Vtq.Value[0, 0];

Solution

  • A bit of background. The official documentation around the two object is

    As you can see the Value is of object type (pretty much every object inherits from object) so you can't access it as an array unless you typecast it (bad idea).

    The fact that it might print as a 2 dimensional array means nothing as I could do anything in C# by overriding the ToString() function.

    There is also the Vtq.ValueType which might help you with case specific handling.