Create an instance with an internal constructor without using ‘new’

It was a surprise for me that Activator.CreateInstance does not create an instance using an internal constructor when its class is declared in another assembly and marked with InternalsVisibleToAttribute pointed to a calling assembly. I’m not sure does it work in the same assembly, didn’t check. But there is a simple solution using reflection. Here is is an example:

typeof(Foo).InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
Advertisements
This entry was posted in .NET, C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s