Casting Arrays?

Hi,

I have a method which returns an object array:

object[] sortArray(object[] input, int[] order);

And I want to be able to cast the array that it returns, for example:

string[] array = (string[])sortArray(input, order);

While this compiles, at run time I get a casting error (InvalidCastException, Specified cast is not valid). How should I be casting the array, or can I cast it at all

Thanks.



Answer this question

Casting Arrays?

  • MylesRip

    here Is a much better way:

    string[] array = Array.ConvertAll<object, string>(input,< xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

        delegate(object obj)

        {

            return (string)obj;

        });

     

    And here is one that doesn’t use generics:

     

    string[] array = new string[input.Length];

    for (int index = 0; index < input.Length; index++)

    {

        array[index] = (string)input[index];

    }



  • WV John

    You should probably iterate through the objects in the list and cast each item separately. In untested code:

    string[] stringArray;

    stringArray = new string[objectsArray.Count]();
    foreach (object obj in objectsArray)
    {
    stringArray[objectsArray.IndexOf(obj)] = obj.ToString();
    }


  • Casting Arrays?