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(",, Version=, Culture=neutral, PublicKeyToken=null");
ConstructorInfo ctor = ty.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];
var inst = ctor.Invoke(new object[] { param1, param2 });

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s