0

I have a base type for all model classes, which provides some basic properties. Some models represent master detail relations, which are stored in property of ObservableCollection<DetailModel>.

I want to access theses detail collections in a generic approach, as shown below.

    public class ModelBase
    {

        public int Id { get; set; }

        public string Description { get; set; }

    }

    public class DaugtherModel : ModelBase
    {

    }

    public class SonModel : ModelBase
    {

    }


    public class MotherModel : ModelBase
    {
        public ObservableCollection<DaugtherModel> Daughters { get; set; } = new ObservableCollection<DaugtherModel>();

        public ObservableCollection<SonModel> Sons { get; set; } = new ObservableCollection<SonModel>();

    }

    class Program
    {
        static void Main(string[] args)
        {


            MotherModel mother = new MotherModel();

            PropertyInfo[] infos = mother.GetType().GetProperties();

            foreach (PropertyInfo motherProp in infos.Where(x => x.PropertyType.Namespace == "System.Collections.ObjectModel").ToList())
            {
                // Here I get an error Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[vererbung.DaugtherModel]' to type 'System.Collections.ObjectModel.ObservableCollection`1[vererbung.ModelBase]'
                foreach (ModelBase child in (ObservableCollection<ModelBase>)motherProp.GetValue(mother))
                {
                    Console.WriteLine(child.Description);
                }
            }
        }
    }

The code throws the following error message:

Unable to cast object of type

'System.Collections.ObjectModel.ObservableCollection'1[vererbung.DaugtherModel]' to type 'System.Collections.ObjectModel.ObservableCollection'1[vererbung.ModelBase]'

How can access the cild objects through the base type?

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Mister 832
  • 1,177
  • 1
  • 15
  • 34
  • 1
    Have you tried casting it as an `IEnumerable`? The thing here is that you can't add a `MotherModel` item to an `ObservableCollection` but you would be able to add it to an `ObservableCollection` so those two are not the same thing. Read here if you want to learn more: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/ –  Jul 26 '19 at 17:40
  • Thank you, the line `(IEnumerable)motherProp.GetValue(mother)` works fine. – Mister 832 Jul 26 '19 at 18:54

1 Answers1

0

You do not need your cast in the foreach of the list, the followig will do:

foreach (ModelBase child in MotherProp.GetValue(mother))
Aldert
  • 4,209
  • 1
  • 9
  • 23
  • This does not work. It won't compile due to object does not contain a public instance definition for 'GetEnumerator' – Mister 832 Jul 26 '19 at 18:55
  • This means you need to go a level deeper, is there something like MotherProp.GetValue(mother).Daughters ? – Aldert Jul 26 '19 at 19:01