Marcel James
Marcel James

Reputation: 874

How can I Create an object and execute a method using reflection?

I have this class:

public class StructTest
{

    public StructTest()
    {

    }

    public void Start()
    {
        // do something
    }

}

I want to dynamically create an instance of the class StructTest and execute its method "Start" using reflection. But the following code is throwing an Exception:

Assembly current = Assembly.GetExecutingAssembly();
        string nomeClasse = "StructTest";

        foreach (var classInAssembly in current.GetTypes().Where(p => p.IsClass).Where(p => p.Name.Equals(nomeClasse)))
        {
            Type type = classInAssembly.GetType();
            var classe = Activator.CreateInstance(type, null); // Here the VS says theres no paramterless contructor for this class without parameters

            IEnumerable<MethodInfo> methodList = classInAssembly.GetMethods().Where(p => p.Name.Equals("Start"));
            MethodInfo method = methodList.First();

            method.Invoke(classe, null);
        }

Upvotes: 1

Views: 658

Answers (1)

King King
King King

Reputation: 63317

foreach (var type in current.GetTypes().Where(p => p.IsValueType && p.Name.Equals(nomeClasse))) {
        var classe = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod("Start");
        method.Invoke(classe, null);
}

Upvotes: 2

Related Questions