2

I'm working on a project where I have to reflect through data models to find out what type is in each property on a data models. I have the code working for all cases except for generic collections. I have to be able to what T is in IList.

I have the following data model

public class ArrryOfObjects
{
    public NestModelNestedClass NestClass { get; set; }
    public int IntObject { get; set; }
    public IList<NestModelNestedClass> ListOfObjects { get; set; }
}

I've seen a couple of examples, like https://stackoverflow.com/a/1043778/136717 on how to do this, but they use the type.GetGenericTypeDefinition() to be get the type. But in my sample I cannot use this because 'type.IsGeneric.Parameter' is false.

I've review Type documentation and don't understand how to do this.

Community
  • 1
  • 1
photo_tom
  • 7,292
  • 14
  • 68
  • 116

1 Answers1

5

Try this:

var t = typeof(ArrryOfObjects)
    .GetProperty("ListOfObjects")
    .PropertyType
    .GetGenericArguments()[0];

This is how it works:

  • From the type of ArrryOfObjects...
  • obtain the property called ListOfObjects...
  • get the type of that property...
  • which we know to be a generic type with at least one type parameter.
  • We get the first type parameter - in your example it should be typeof(NestModelNestedClass)

P.S. GetGenericTypeDefinition gets you typeof(IList<>), the generic type of which IList<NestModelNestedClass> is a generic instance.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523