Instancing a class with an internal constructor
An alternative would be to nominate the calling assembly as a "friend" assembly.
Simply add this to AssemblyInfo.cs file of the assembly containing the internal constructor:
[assembly: InternalsVisibleTo("Calling.Assembly")]
If you don't have access to the assembly, you can also call the constructor directly (using Reflection):
MyClass obj = (MyClass) typeof(MyClass).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, Type.EmptyTypes, null).Invoke(null);
A FormatterServices.GetUninitializedObject method exists (Namespace: System.Runtime.Serialization), it supposedly calls no constructors, if you really want to try out that approach.
This is a method derived from this answer:
public static T CreateInstance<T>(params object[] args)
{
var type = typeof (T);
var instance = type.Assembly.CreateInstance(
type.FullName, false,
BindingFlags.Instance | BindingFlags.NonPublic,
null, args, null, null);
return (T) instance;
}
Example usage (this is a Kinect SDK type that I needed to create for unit tests):
DiscreteGestureResult a = CreateInstance<DiscreteGestureResult>(false, false, 0.5f);