Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# PropertyInfo (Generic)

Tags:

c#

reflection

Lets say i have this class:

class Test123<T> where T : struct
{
    public Nullable<T> Test {get;set;}
}

and this class

class Test321
{
   public Test123<int> Test {get;set;}
}

So to the problem lets say i want to create a Test321 via reflection and set "Test" with a value how do i get the generic type?

like image 713
Peter Avatar asked Dec 05 '22 05:12

Peter


1 Answers

Since you are starting from Test321, the easiest way to get the type is from the property:

Type type = typeof(Test321);
object obj1 = Activator.CreateInstance(type);
PropertyInfo prop1 = type.GetProperty("Test");
object obj2 = Activator.CreateInstance(prop1.PropertyType);
PropertyInfo prop2 = prop1.PropertyType.GetProperty("Test");
prop2.SetValue(obj2, 123, null);
prop1.SetValue(obj1, obj2, null);

Or do you mean you want to find the T?

Type t = prop1.PropertyType.GetGenericArguments()[0];
like image 182
Marc Gravell Avatar answered Dec 20 '22 07:12

Marc Gravell