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.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.
Instance constructorInstance constructors can have public, private, protected, external, or internal modifiers.
Constructor code or any internal method used only by constructor are not included in final code. A constructor can be either public or internal.
An instance constructor is a method whose task is to create an instance of a class. A constructor is a member function whose task is to initialize the objects of its class, in other words it is a method of a class that executes when the class's objects are created.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With