Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 920
Michael Stum Avatar asked Jul 29 '09 11:07

Michael Stum


People also ask

How do you instantiate an internal class?

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.

Can constructor be internal in C#?

Instance constructorInstance constructors can have public, private, protected, external, or internal modifiers.

Can constructor be internal?

Constructor code or any internal method used only by constructor are not included in final code. A constructor can be either public or internal.

What is an instance constructor?

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.


2 Answers

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); 
like image 180
Philippe Leybaert Avatar answered Sep 18 '22 09:09

Philippe Leybaert


A FormatterServices.GetUninitializedObject method exists (Namespace: System.Runtime.Serialization), it supposedly calls no constructors, if you really want to try out that approach.

like image 34
Kenan E. K. Avatar answered Sep 18 '22 09:09

Kenan E. K.