none
Call Method from string and get the result RRS feed

  • Question

  • i have a one dll which is contains lot of class. 

    dll is already added in project as a referance. 

    i have a class name and it's method but in string format like "ClassA.MehodB()".

    how can i call this method in c# also how to get the return result after execute function.

    Please Suggest me some way to archive gole

    thanks in advance 

    Chirag Sr. Sw.Developer Ahmedabad

    Thursday, November 21, 2013 8:44 AM

Answers

  • Hi,

    You can dynamicaly create instance and call method of it - for example:

    public object Invoke(string typeName, string methodName)
    {
        Type type = Type.GetType(typeName);
        object instance = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod(methodName);
        return method.Invoke(instance, null);
    }

    regards,
    RR

    • Proposed as answer by JA Reyes Thursday, November 21, 2013 8:59 AM
    • Marked as answer by Eason_H Friday, November 29, 2013 1:35 AM
    Thursday, November 21, 2013 8:56 AM
  • Here is an example.

    public class ClassA
    {
    	public void MethodA()
    	{
    		Console.WriteLine("Hello World");
    	}
    }
    
    
    void Main()
    {
    	// Gets the default ctor of the class from a string (requires the Full Qualified Name to the class that is the <namespace name>+<class name>).
    	var classACtor = Type.GetType("UserQuery+ClassA").GetConstructor(Type.EmptyTypes);
    	
    	// Creates the object by calling the ctor, you can also use Activator (but it's slower).
    	var classA = classACtor.Invoke(null);
    	
    	// Gets the method.
    	var methodA = classA.GetType().GetMethod("MethodA");
    	
    	// Calls the targeted method.
    	methodA.Invoke(classA, null);
    	
    	/* NOTES: 
    		a. I assume that both the class and the method are public and they are not static! otherwise, you need to provide the correct bindings
    		b. I really prefer to do these kind of things with LINQ expressions nowadays but to make it simple I used reflection
    	*/
    	
    	
    }

    To really get it to work the way I think you want it to work you will have to build a C# compiler without the completion component that will take the source as a string and either emit it or reflect it at run-time, however, it's a lot of work so you might want to check Rolslyn - Compiler as a Service or 3rd party libs that will allow you to evaluate expressions or full source code, alternatively, you can use CodeDom.


    Regards,

    Eyal Shilony



    • Edited by Eyal SolnikModerator Thursday, November 21, 2013 9:51 AM
    • Proposed as answer by JA Reyes Thursday, November 21, 2013 12:57 PM
    • Marked as answer by Eason_H Friday, November 29, 2013 1:35 AM
    Thursday, November 21, 2013 9:12 AM
    Moderator

All replies

  • If your MethodB is a static one in ClassA, please directly do as what you gave us above.

    If not, please:

    ClassA a = new ClassA();

    a.MethodB();


    ASP.NET Questions
    Other Discussions
    FreeRice Donate
    Issues to report

    Thursday, November 21, 2013 8:47 AM
  • Hi,

    You can dynamicaly create instance and call method of it - for example:

    public object Invoke(string typeName, string methodName)
    {
        Type type = Type.GetType(typeName);
        object instance = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod(methodName);
        return method.Invoke(instance, null);
    }

    regards,
    RR

    • Proposed as answer by JA Reyes Thursday, November 21, 2013 8:59 AM
    • Marked as answer by Eason_H Friday, November 29, 2013 1:35 AM
    Thursday, November 21, 2013 8:56 AM
  • Here is an example.

    public class ClassA
    {
    	public void MethodA()
    	{
    		Console.WriteLine("Hello World");
    	}
    }
    
    
    void Main()
    {
    	// Gets the default ctor of the class from a string (requires the Full Qualified Name to the class that is the <namespace name>+<class name>).
    	var classACtor = Type.GetType("UserQuery+ClassA").GetConstructor(Type.EmptyTypes);
    	
    	// Creates the object by calling the ctor, you can also use Activator (but it's slower).
    	var classA = classACtor.Invoke(null);
    	
    	// Gets the method.
    	var methodA = classA.GetType().GetMethod("MethodA");
    	
    	// Calls the targeted method.
    	methodA.Invoke(classA, null);
    	
    	/* NOTES: 
    		a. I assume that both the class and the method are public and they are not static! otherwise, you need to provide the correct bindings
    		b. I really prefer to do these kind of things with LINQ expressions nowadays but to make it simple I used reflection
    	*/
    	
    	
    }

    To really get it to work the way I think you want it to work you will have to build a C# compiler without the completion component that will take the source as a string and either emit it or reflect it at run-time, however, it's a lot of work so you might want to check Rolslyn - Compiler as a Service or 3rd party libs that will allow you to evaluate expressions or full source code, alternatively, you can use CodeDom.


    Regards,

    Eyal Shilony



    • Edited by Eyal SolnikModerator Thursday, November 21, 2013 9:51 AM
    • Proposed as answer by JA Reyes Thursday, November 21, 2013 12:57 PM
    • Marked as answer by Eason_H Friday, November 29, 2013 1:35 AM
    Thursday, November 21, 2013 9:12 AM
    Moderator
  • If your MethodB is a static one in ClassA, please directly do as what you gave us above.

    If not, please:

    ClassA a = new ClassA();

    a.MethodB();

    It's irrelevant mate so you should either delete it or read the question again and edit it; otherwise, you may want to tell us why or what makes it relevant to this topic.

    Regards,

    Eyal Shilony

    Thursday, November 21, 2013 9:18 AM
    Moderator
  • Thanks Radosław Roszczyk and Eyal Shilony both answer is work's fine 

    thanks for your great help


    Chirag Sr. Sw.Developer Ahmedabad

    Thursday, November 21, 2013 12:24 PM
  • Hi @Chirag,

    Try to mark as answered those responses that would be useful for you.

    This will help other users with your same issue to find the right responses.

    Regards.


    Please remember to Vote & "Mark As Answer" if this post is helpful to you.
    Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.

    Thursday, November 21, 2013 12:56 PM
  • Hi,

    You can dynamicaly create instance and call method of it - for example:

    public object Invoke(string typeName, string methodName)
    {
        Type type = Type.GetType(typeName);
        object instance = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod(methodName);
        return method.Invoke(instance, null);
    }

    regards,
    RR

    this is working fine if i am add one class with same namespace or different but in to the same project but it's give error if i am create a different project and reference that project in my application as a dll. Error is below 

    Type type2 = Type.GetType("EntityScripting.Knd");
    object instance = Activator.CreateInstance(type2);
    MethodInfo method2 = type2.GetMethod("kndtest");
    var k = method2.Invoke(instance, new object[1] { ("hello") });

    Error is 

    Value cannot be null.
    Parameter name: type

    var ClassType = Type.GetType("EntityScripting.Knd").GetConstructor(Type.EmptyTypes);
    var ClassInstant = ClassType.Invoke(null);
    var ClassMethod = ClassInstant.GetType().GetMethod("kndtest");
    var Result = ClassMethod.Invoke(ClassInstant, new object[1] { (XMLResponse) });
    Error is 
    Object reference not set to an instance of an object.


    Chirag Sr. Sw.Developer Ahmedabad


    • Edited by [Chirag] Monday, November 25, 2013 1:46 PM
    Monday, November 25, 2013 1:07 PM
  • Hi Chirag,

    Could you tell me which line error?

    We cannot do much with what you gave us. Have you taken basic debugging steps to find out what might be going wrong? You can find many information about error and how to solve it from the error message.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, November 28, 2013 4:40 AM