3
String ClassName =  "MyClass"
String MethodName = "MyMethod"

I would like to achieve:

var class = new MyClass; 
MyClass.MyMethod();

I saw some e.g. with reflection , but they only show , either having a method name as string or class name as string, any help appreciated.

3
  • 4
    Why do you need to do that? I'm asking because most reflection questions are XY-Problems in my experience. Commented Mar 13, 2015 at 13:59
  • Show us what you have tried and where you get stucked. Commented Mar 13, 2015 at 14:00
  • 1
    If you have seen an example that uses reflection to create a class and another to call a method then just combine them and if it doesn't work post the code and results. Commented Mar 13, 2015 at 14:01

2 Answers 2

10
// Find a type you want to instantiate: you need to know the assembly it's in for it, we assume that all is is one assembly for simplicity
// You should be careful, because ClassName should be full name, which means it should include all the namespaces, like "ConsoleApplication.MyClass"
// Not just "MyClass"
Type type = Assembly.GetExecutingAssembly().GetType(ClassName);
// Create an instance of the type
object instance = Activator.CreateInstance(type);
// Get MethodInfo, reflection class that is responsible for storing all relevant information about one method that type defines
MethodInfo method = type.GetMethod(MethodName);
// I've assumed that method we want to call is declared like this
// public void MyMethod() { ... }
// So we pass an instance to call it on and empty parameter list
method.Invoke(instance, new object[0]);
Sign up to request clarification or add additional context in comments.

Comments

6

Something similar, probably with more checks:

string typeName = "System.Console"; // remember the namespace
string methodName = "Clear";

Type type = Type.GetType(typeName);

if (type != null)
{
    MethodInfo method = type.GetMethod(methodName);

    if (method != null) 
    {
        method.Invoke(null, null);
    }
}

Note that if you have parameters to pass then you'll need to change the method.Invoke to

method.Invoke(null, new object[] { par1, par2 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.