Search code examples
c#arraysgenericsobjectreadonly-collection

object[] from ReadOnlyCollection<T>


I have an object that I ended up with via a reflection call:

object readOnlyCollectionObject = propertyInfo.GetValue(someEntity, null);

I know this object is a generic ReadOnlycollection. It could be a ReadOnlyCollection<Cat>, ReadOnlyCollection<Dog>, etc. For argument sake, lets just say it is a ReadOnlyCollection<T>.

Even though a Dog derives from an object, I know that a ReadOnlyCollection<Dog> does not derive from a ReadOnlyCollection<object>. So even if I use reflection to call the CopyTo method I still need to know the specific type of ReadOnlyCollection, which is what I want to avoid.

I want to know how to get all the elements out of the ReadOnlyCollection as an array of object references without having to know the specific type (T) of the ReadOnlyCollection<T>.


Solution

  • Many other answers mention Cast() and ToArray, those all have a problem with the type. As you say, you won't know which specialized IEnumerable your property will implement. However, you can be sure that they will all implement the non-generic ICollection interface.

    ICollection readOnlyCollectionObject = (ICollection)propertyInfo.GetValue(someEntity, null);
    object[] objs = new ArrayList(readOnlyCollectionObject).ToArray();
    

    or

    ICollection readOnlyCollectionObject = (ICollection)propertyInfo.GetValue(someEntity, null);
    object[] objs = new object[readOnlyCollectionObject.Count];
    for (int i = 0; i < readOnlyCollectionObject.Count; i++)
        objs[i] = readOnlyCollectionObject[i];
    

    Edit: Forgot to update the cast from IEnumerable to ICollection