0

I have a method(methodA) accepting T as a generic type and all classes (C1,C2,..) for T have a List parameter having different names and types (L).

public class C1{
    public List<L1> C1List{get;set;}=new List<L1>();
}

public class C2{
    public List<L2> C2List {get;set;}=new List<L2>();
}

I want to call another method (methodB) accepting TX as a generic type from methodA and methodB should be called with the type of the List (L).

My attempt to fix the problem was incomplete as I couldn't find a way to set the TypeOfPi.

public T methodA<T>(){
    var r= Activator.CreateInstance<T>();
    var pi= r.GetType().GetProperties().First(p => p.PropertyType.Name == "List`1");

    pi.SetValue(r,methodB<TypeOfPi>());

    return r;
}

public List<TX> methodB<TX>(){
    var r=new List<TX>();
    .
    .
    return r;
}

Is there a way to set TypeOfPi or any other way to solve my problem?

aza
  • 115
  • 13
  • You need to fix code samples. What is `myReturn`? `public C1 {` is it class? `=new C1List();` not valid C# syntax. – Roman Jun 22 '22 at 10:22
  • I have fixed code samples. C1,C2 are classes. Each has a List of different types. – aza Jun 22 '22 at 10:32
  • I can solve my problem if I send type of List as T2 and modify methodA and call methodB. But if I do so, even if the type of the List can be extracted from T, I have to send the type of the List each time which seems to me as redundency. – aza Jun 22 '22 at 10:40

1 Answers1

1

From you code in methodA you need to use reflection to call methodB:

public T methodA<T>()
{
    var instance = Activator.CreateInstance<T>();
    var listProperty = instance.GetType().GetProperties().First(p => p.PropertyType.Name == "List`1");
    
    var listGenericArgType = listProperty.PropertyType.GetGenericArguments().First();
    
    var methodB = this.GetType().GetMethod("methodB").MakeGenericMethod(listGenericArgType);
    var methodBResult = methodB.Invoke(this, null);
     
    listProperty.SetValue(instance, methodBResult);

    return instance;
}
Roman
  • 11,966
  • 10
  • 38
  • 47
  • listProperty.GetType().GetGenericArguments().First() raises an error since listProperty.GetType().GetGenericArguments() returns 0 records. – aza Jun 22 '22 at 11:27
  • @aza, you're right, it should be `var listGenericArgType = listProperty.PropertyType.GetGenericArguments().First();`, edited my answer – Roman Jun 22 '22 at 11:34