0

I have one class which i try to create with the help of Avtivator.CreateInstance because i am getting the class name at run time as an string. So, in that class i have some method with one parameter of type List, now my question is how to call this type of method using MethodInfo. e.g.

Class XHospital{

    private string HospitalName;
    private IList<string> docList;
    public void SetDoctorList(List<string> docList){

        this.docList = docList;
       // some other code snippet here after getting docList
    }
    // .... rest of the code
}

Now creating Hospital class and calling method

public void SetHospitalDetails(string hospitalName, string methodName){

    Type NewType = Type.GetType(hospitalName);
    Object NewClass = Activator.CreateInstance(NewClass, new object[]{});
    MethodInfo method = NewType.GetMethod(methodName);
    IList<string> docs = new List<string>(){ "doc1", "doc2" };
    method.Invoke(NewClass, new object[] { docs });//-------------  here i am 
       //  getting exception stating ...
       /*   Object of type 'System.Collections.Generic.List`1[System.Object]' 
            cannot be converted to type 
            'System.Collections.Generic.List`1[System.String]' */
}

Please help what i am doing wrong... Note: I am not allow to make any change in XHospital class. So i can't handle it by myself.*** Thanks in advance.

Timothy Groote
  • 8,614
  • 26
  • 52
Md IstiyaQ
  • 21
  • 3
  • Possible duplicate of [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – SᴇM Oct 13 '17 at 07:19

2 Answers2

0

From documentation:

An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked.

The fix is to NOT make your variable more abstract (IList<String>) if it is the exact concrete type (List<String>) you need to pass in. So try this instead:

 List<string> docs = new List<string>(){ "doc1", "doc2" };
 method.Invoke(NewClass, new object[]{docs} );
Imre Pühvel
  • 4,468
  • 1
  • 34
  • 49
0

Your code is right except: Object NewClass = Activator.CreateInstance(NewClass, new object[]{}); It should be Object NewClass = Activator.CreateInstance(NewType, new object[]{});

It works well. If you still have problems, try set the field value directely. field.SetValue(NewClass, anything);

WildWind
  • 162
  • 12