Click here to Skip to main content
15,846,144 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Assigning and Using Anonymous Arrays

I have an object that at runtime can be an array of unknown Type. I have a function that will convert an array to a string generic if I know its Type. But I don't always know the Type coming in. Here is a code snippet:
C#
object val = getter.Invoke(obj, null);
                
string sval;

if (val == null)
    sval = "[Null]";
else
{
    Type t = val.GetType();
    if (t.IsArray == true)
    {
        object[] array = val as object[];
        sval = ArrayToStringGeneric(array, ", ");
    }
else
    sval = val.ToString();
}

When I try to assign val to array like above array come up null and my call to ArrayToStringGeneric fails. If I change the line:
C#
object[] array = val as object[];

to:
C#
int[] array = val as int[];

The assignment works and array has values that work, but I will not always know the Type. Is there a way to make this work for all unknown Types at runtime?

Thanks,
E
Posted
Updated 9-Dec-10 11:45am
v3

This should work:
C#
// Your initial array stored in an object.
object o = new int[] { 1, 2, 3 };

// Cast to array.
Array a = (Array)o;

// Create object array to hold items.
object[] items = new object[a.Length];

// Move items to object array.
for (int i = 0; i < a.Length; i++)
{
    items[i] = a.GetValue(i);
}

// Show result.
for (int j = 0; j < items.Length; j++)
{
    MessageBox.Show(items[j].ToString());
}
 
Share this answer
 
Comments
Dalek Dave 9-Dec-10 17:30pm    
Good Answer.
Thanks tons. That seams to be doing the trick. Been racking my head for hours. Here is my code change from your suggestion. I'll most likely clean it up a bit more but, thanks again.

object val = getter.Invoke(obj, null);

string sval;
if (val == null)
sval = "[Null]";
else
{
Type t = val.GetType();
if (t.IsArray == true)
{
Array a = (Array)val;
object[] array = new object[a.Length];
for (int i = 0; i < a.Length; i++)
{
array[i] = a.GetValue(i);
}
sval = ArrayToStringGeneric(array, ", ");
}
else
sval = val.ToString();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900