Tawani
Tawani

Reputation: 11198

Convert an object that is an array to an array of objects

How do you (in C#) convert an object that is an array to an array of objects

Something in the following format:

bool Compare(object valueToCompare)
{
   if(valueToCompare.IsArray())
   {
      foreach(var value in (valueToCompare as Array)){
          if(Compare(value));
             return true;
          return Compare(value);
      }
   }
   else
       return Compare(valueToCompare);
}

NOTE: The code above doesn't do much. I'm just prototyping.

Upvotes: 1

Views: 1372

Answers (1)

Adam Robinson
Adam Robinson

Reputation: 185623

Assuming that the following are true:

  • valueToCompare is an array of reference types (not, say, an int[] or DateTime[])
  • The array that valueToCompare is one dimensional (so either declared as a one-dimensional array or a jagged array)

You can cast directly to an object[] instead of Array.

bool Compare(object valueToCompare)
{
   Type t = valueToCompare.GetType();

   if(t.IsArray() && !t.GetElementType().IsValueType && t.GetRank() == 1)
   {
      foreach(var value in (valueToCompare as object[]))
          return Compare(value);
   }
   else
   {
       return Compare(valueToCompare);
   }
}

If your array is of value types, then you're basically out of luck.

If your array is multi-dimensional, then you'll just have to write similar checks to account for as many dimensions as you want to support.

NOTE: As you've written it, this function will just call itself recursively (the else branch calls itself with the same parameters) and eventually result in a StackOverflowException. I don't believe this is what you intended to do, but I have left it as-is since I don't know what you actually wanted to do.

Additionally this won't actually compile. I'm not sure what your loop is intended to compare; as it is, it will just compare with the first element of the array, but if the array is empty then it won't return a value (hence the compilation error).

What are you trying to do here?

Upvotes: 3

Related Questions