Click here to Skip to main content
15,919,341 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a model with property of generic List <t>. how can i find the type of that List dynamically via reflection.
public class Sample{

public int Id{get; set;}

public List<int?> Prop1{get; set;}
public List<myclass> Prop2{get; set;}

how can find the type of List like int? or MyClass

What I have tried:

PropertyInfo[] Props = typeof(SampleSample).GetProperties(BindingFlags.Public | BindingFlags.Instance);

i am able to find the property is generic List
Props["Prop1"].PropertyType.IsGenericType && Props["Prop1"].PropertyType.GetGenericTypeDefinition() == typeof(List<>)

but not able to find the type of list.
Updated 12-May-21 4:51am

1 solution

Here's an example using the Type.GetGenericArguments()[^] method:
public class Example
  public List<int?> Target { get; set; }

Type type = typeof(Example).GetProperty("Target").PropertyType;
Type generic = type.GetGenericArguments().First();

Console.WriteLine($"Type {type} has generic argument {generic}");

The method returns an array so you can either use First() to select the first element, or use the standard array indexer [0]
Share this answer
Maciej Los 12-May-21 12:22pm    
BillWoodruff 12-May-21 21:03pm    
Siddharth Rai 12-May-21 23:39pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900