Question

I'm migrating some C# code to C++ CLI, And I need cast a managed array of ushort

This is the C# code

foreach(ushort v in mo.Properties["ChassisTypes"].Value as ushort[])

And this is my attempt so far

for each(USHORT ^v in (USHORT[] ^) mo.Properties["ChassisTypes"].Value)

unfortunatly this is give me some errors

1 IntelliSense: incomplete type is not allowed

2 IntelliSense:expected a ')'

3 IntelliSense: expression must have class type

What is the proper way to cast this kind of arrays in C++ CLI?

Was it helpful?

Solution

You can try the following code:

for each(UInt16 v in (array<UInt16>^)(mo->Properties["ChassisTypes"]->Value))
{
}

For safety you can use dynamic_cast as @Ben said.

array<UInt16>^ chassisTypes = dynamic_cast<array<UInt16>^>(mo->Properties["ChassisTypes"]->Value);
if (chassisTypes != nullptr)
    for each(UInt16 v in chassisTypes)
    {
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top