-1

I have an object that could be any type. I have a check to see if its an array and then I need to convert it to a List<object> if it is. I am having trouble handling the case where its a primitive array as shown below. It is not an IEnumerable<object> in this case. Note I cannot use LINQ in this framework:

object value = SomeFunction();
if( value.GetType().IsArray )
{
  try
  {
     List<object> l = new List<object>( (IEnumerable<object>)value );
  }
  catch(Exception e)
  {
    //here its failing because its no an object
  }
}

`

D Stanley
  • 149,601
  • 11
  • 178
  • 240
user2292539
  • 245
  • 1
  • 11
  • 1
    Why do you not iterate it and add it to the list in that case? – Der Kommissar May 21 '15 at 18:12
  • Is the array known to be single dimensional, or might it be multi-dimensional? – Servy May 21 '15 at 18:13
  • single dimension. I can itterate it, but since i don't know the type i can't use enumerable like above. The only idea i could come up with was reflection using the get method and count. Seems slow though. – user2292539 May 21 '15 at 18:24
  • Note that your question would be more accurate if you use "value type" instead of "primitive type". You can't convert arrays of `struct`s or `decimal`s to `IEnumerable` either – D Stanley May 21 '15 at 18:28

1 Answers1

3

You can't cast to IEnumerable directly because covariance doesn't work for value types. The Linq answer would be to call Cast to cast each element of the underlying array to an object (boxing them in the process).

I'm not sure what you mean by "I can't use Linq", but you could replicate what Linq's Cast would do:

object value = SomeFunction();
if( value.GetType().IsArray )
{
  try
  {
     List<object> l = new List<object>();
     foreach(object o in (IEnumerable)value) // implicitly cast each item to object
     {
        l.Add(o);
     }
  }
  catch(Exception e)
  {
    //here its failing because its no an object
  }
}

If you want to use covariance for reference types you can check the underlying type of the array at runtime:

List<object> l = new List<object>();
if(value.GetType().GetElementType().IsValueType)
{
    foreach(object o in (IEnumerable)value)
    {
        l.Add(o);
    }
}
else
{
    l.AddRange((IEnumerable<object>)value);
}
Community
  • 1
  • 1
D Stanley
  • 149,601
  • 11
  • 178
  • 240