Laser42
Laser42

Reputation: 744

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.

Upvotes: 0

Views: 1482

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499800

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);

Upvotes: 1

Related Questions