Casper_2211
Casper_2211

Reputation: 1091

Activator.CreateInstance returning error now

I was initially using the following method - which was working fine

var obj = Activator.CreateInstance("MyProject","MyProject.MyImpl");

Now I am getting an error at the above line and the error is:

Exception has been thrown by the target of an invocation.

Any suggestions on what might be going wrong ?

Upvotes: 4

Views: 3654

Answers (2)

Ran
Ran

Reputation: 6159

The easiest would be to set a breakpoint in the constructor of the MyImpl class and debug it.

One tricky problem you might be having is if the exception is actually not thrown directly by the constructor, but by some field initializer.

For example the following would cause the behavior you described, even though there is no explicit constructor that could throw anything.

public class MyImpl
{
    private int something = ThisMethodThrows();

    private int ThisMethodThrows()
    {
        throw new Exception();
    }
}

Upvotes: 5

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

An exception is being thrown in the constructor of the object. Turn exceptions on in Visual Studio and it should break when that constructor throws.

Upvotes: 3

Related Questions