Help - Accessing the UInt16 array ref'ed in a collectionitem

  • Thread starter Thread starter Norman
  • Start date Start date
N

Norman

I have a collection that can have a reference to various types of
arrays.

String was easy:
...
string[] sPropertyArray = (string[])oReturn[oProperty.Name];
foreach( string sItem in sPropertyArray )
{
...

How do I handle a UInt16 array?

I have tried( and various permutations):
...
uint[] iPropertyArray = (uint[])TypeConverter.ConvertTo(
oReturn[oProperty.Name] , typeof( System.UInt32[] ) );
foreach( uint iItem in iPropertyArray )
{
...

Continue to get:

error CS0120: An object reference is required for the nonstatic
field, method, or property
'System.ComponentModel.TypeConverter.ConvertTo(object, System.Type)'

Thanks,
Norman
 
Norman said:
I have a collection that can have a reference to various types of
arrays.

String was easy:
...
string[] sPropertyArray = (string[])oReturn[oProperty.Name];
foreach( string sItem in sPropertyArray )
{
...

How do I handle a UInt16 array?

I have tried( and various permutations):
...
uint[] iPropertyArray = (uint[])TypeConverter.ConvertTo(
oReturn[oProperty.Name] , typeof( System.UInt32[] ) );
foreach( uint iItem in iPropertyArray )
{
...

Why did you try that? Why not just:

uint[] iPropertyArray = (uint[]) oReturn[oProperty.Name];

What does oReturn[oProperty.Name] actually give you?
 
uint[] iPropertyArray = (uint[]) oReturn[oProperty.Name];
You get this at run time:

Unhandled Exception: System.InvalidCastException: Specified cast is
not valid.

If you try this:

Console.WriteLine( oReturn[oProperty.Name] )

Output
System.UInt16[]

If it happened to be a string array:

Output:
System.String[]

That's why I cast it and looped through the string array and output
the actual values.

I need to do the same thing with UInt16[], UInt32[] and UInt8[].

Jon Skeet said:
Why did you try that? Why not just:

uint[] iPropertyArray = (uint[]) oReturn[oProperty.Name];

What does oReturn[oProperty.Name] actually give you?
Norman said:
I have a collection that can have a reference to various types of
arrays.

String was easy:
...
string[] sPropertyArray = (string[])oReturn[oProperty.Name];
foreach( string sItem in sPropertyArray )
{
...

How do I handle a UInt16 array?

I have tried( and various permutations):
...
uint[] iPropertyArray = (uint[])TypeConverter.ConvertTo(
oReturn[oProperty.Name] , typeof( System.UInt32[] ) );
foreach( uint iItem in iPropertyArray )
{
...
 
Norman said:
uint[] iPropertyArray = (uint[]) oReturn[oProperty.Name];
You get this at run time:

Unhandled Exception: System.InvalidCastException: Specified cast is
not valid.

Then presumably it hasn't returned an array of uints! The same would go
for your string case if you weren't returning strings.
If you try this:

Console.WriteLine( oReturn[oProperty.Name] )

Output
System.UInt16[]

Ah... those are ushorts, not uints. Change your code to use ushort
instead of uint and you should be fine.
 
Back
Top