Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Replacement for.NET ArrayList.ToArray(Type) in Silverlight

Below is a simple method I wrote (extremely simplified down so I hope it still gets the jist across) for taking a string representation of an array's elements in a string, and converting them into an actual array of those values. t is the type of the array.

DeserializeArray(string sArrayElements, out Array aValues, Type t)
{
    string[] sValues = ProcessArrayElements(sArrayAsString);
    ArrayList alValues = new ArrayList(sValues.Length);
    for(int i = 0; i < sValues.Length; ++i)
        alValues.Add(ProcessValue(sValues[ i ] ));
    aValues = alValues.ToArray(t.GetElementType());
    return true;
}

I would then use this method with the code below. propertyInfo is the property of an object that in this case .IsArray() == true. sArrayElements is just the string that contains the string representation of the array ("val1,val2,...,valN")

Array aValues;
if (DeserializeArray(sArrayElements, out aValues, propertyInfo.PropertyType))
    propertyInfo.SetValue(oObject, aValues, null);
else
    throw new FormatException("Unable to parse Array Elements: " + sArrayElements);

This works beautifully in .NET, but not in Silverlight because the ArrayList object is marked as Internal or something (can not use type because access level blah blah blah).

So I am looking for an alternative to the ArrayList.ToArray(Type). I can not just use a List<object>.ToArray() because the PropertyInfo.SetValue() call will bawk at trying to make an object[] into an Int32[] or the like.

I have tried in the DeserializeArray() method to do something like aValues = Array.CreateInstance(t.GetElementType()) but I can not use [] to assign the values and you can not assign values to the foreach(obj in objects).

I then tried changing the aValues parameter to a generic object[] array but i get the same conversion (boxing/unboxing) errors at run time when calling the Array.CreateInstance().

So yeah; I am trying to find a solution to this problem for Silverlight 4. Any help would be greatly appreciated :)

  • James
like image 677
James Avatar asked May 24 '26 12:05

James


1 Answers

Not tested, but I think this should do what you want:

DeserializeArray(string sArrayElements, out Array aValues, Type t) 
{ 
    string[] sValues = ProcessArrayElements(sArrayAsString); 
    aValues = new Array[sValues.Length];
    for(int i = 0; i < sValues.Length; ++i) 
        aValues.SetValue(Activator.CreateInstance(t,ProcessValue(sValues[i])),i); 

    return true; 
}
like image 79
Michael Goldshteyn Avatar answered May 26 '26 02:05

Michael Goldshteyn