Instancing a class with an internal constructor
I have a class whose constructor is defined as internal, which means I cannot instantiate it. While that may make sense, I would still like to do it once for debugging and research purposes.
Is it possible to do so with Reflection? I know I can access Private/Internal Members, but can I call an internal constructor?
Or, as the constructor does nothing important, can I use reflection to say "Look, just give me an instance of the class without calling the constructor, I'll do it's work manually"?
Performance and "Stability" is not an issue here, as it's not production code.
Edit: Just as clarification: Sadly, I don't control the other assembly and don't have it's source code, I merely try to understand how it works as it's documentation is next to non-existent, but I am supposed to interface with it.
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);
If you want to avoid reflection, you can use expressions. Here is an example of calling a private constructor with a string value.
private static Func<string, T> CreateInstanceFunc()
{
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var ctor = typeof(T).GetConstructors(flags).Single(
ctors =>
{
var parameters = ctors.GetParameters();
return parameters.Length == 1 && parameters[0].ParameterType == typeof(string);
});
var value = Expression.Parameter(typeof(string), "value");
var body = Expression.New(ctor, value);
var lambda = Expression.Lambda<Func<string, T>>(body, value);
return lambda.Compile();
}