-1

I have a class typed like this:

public class MyClass{
    public List<Myclass1> mc {get;set;}
    public List<Myclass2> mc2 {get;set;}
}

public class Myclass1{
    public string MyString{get;set}
    public string Mystring2 {get;set}
}

How can i get the property List of Myclasse1 when i'm accessing MyClass members by reflection like that:

foreach (var p in MyClass.GetType().GetProperties()){
 //Getting Members of MyClass
 //Here i need to loop through the members name of Myclass1, MyClass2,etc...
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86

1 Answers1

1

You need something like this:

foreach (var p in typeof(MyClass).GetProperties())
{
    if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
    {
        Type listOf = p.PropertyType.GetGenericArguments().First();
    }
}

I've taken the liberty of changing MyClass.GetType(). to typeof(MyClass) since I think this is what you meant.

Basically we check that the property type (e.g. typeof(List<Myclass1>)) is created from an open List<>, and then get the first generic argument (Myclass1).

Try it online.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86