Search code examples
c#collectionscastingentity-framework-core.net-5

C# How to cast object to ICollection of objects


I have a variable which I get from reflections using this syntax (property is a string):

            T entity = DbContext.Set<T>()
               .Include(property)
               .FirstOrDefault(x => x.Id == key);
            var navPropertyCollection = Properties
               .FirstOrDefault(p => p.Name == property)
              ?.GetValue(entity);

navPropertyCollection is an object, but in a class it's declared as ICollection<MyClass> and initialized as List<MyClass>. This is working:

            var navPropertyCollection = Properties
               .FirstOrDefault(p => p.Name == property)
              ?.GetValue(entity) as List<MyClass>;

But I don't know MyClass (and don't need to is this method at all)! I only know it's child of MyBaseClass. I need to cast it into something like ICollection<dynamic>, ICollection<object>, ICollection<MyBaseClass>, List<dynamic>, List<object> or List<MyBaseClass>. But these casts doesn't work. Casting to IEnumerable<object> or IEnumerable<MyBaseClass> works, but this is not the option because later I need to call method Add(), and changes are not marked in my DbContext.


Solution

  • If you're certain that the value of the property will be a List<T> or some other generic collection that implements the non-generic IList interface, I'd suggest casting to that. (I would cast rather than using as though, to avoid masking unexpected types.)

    So:

    var navPropertyCollection = (IList) Properties
        .FirstOrDefault(p => p.Name == property)
        ?.GetValue(entity);