1

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

1 Answer 1

2
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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I Did it now, and it keeps throwing "No parameterless constructor defined for this object."
@WilnerAvila be sure that you have a parameterless constructor defined in your struct like the code you posted.
@WilnerAvila your code has something wrong (fairly much), see my code if it works now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.