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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. My actual code was basically same as yours, except of [0] on GetGenericArguements().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.