Search code examples
c#listgenericstypespropertyinfo

Call a method accepting TX as a generic type from another method with Generic Type T having List(L), with the type of (L) in C#


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?


Solution

  • 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;
    }