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.
C#
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:

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

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

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

1 solution

Here's an example using the Type.GetGenericArguments()[^] method:
C#
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
 
Comments
Maciej Los 12-May-21 12:22pm    
5ed!
BillWoodruff 12-May-21 21:03pm    
+5
Siddharth Rai 12-May-21 23:39pm    
Thanks,

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