Call private or internal constructors using reflection

Sometimes you want to get past the object oriented barriers that C# throws up.
A while ago now I wanted to instantiate a class that only had internal constructors, here is a useful snippet of how I achieved this:
// Use reflection to call private or internal constructors
Type ty = Type.GetType("assembly.name.space.name.myclass, assembly.name.space.name, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
ConstructorInfo ctor = ty.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];
var inst = ctor.Invoke(new object[] { param1, param2 });

Advertisements

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