29

I am trying to use reflection to create instance of a class. But it is sealed internal and has private constructor. I wonder how can i initiaise it and as its part of framework, I can only use reflection to take it out?

internal sealed class ABC
{
    private ABC(string password){}
    public static ABC Create(string password){};
}

Added: System.ServiceModel.Channels.SelfSignedCertificate is the internal class I am trying to use

2
  • 1
    You want to call the private constructor or call the static Create method?
    – Jeff Cyr
    Jan 7, 2010 at 20:00
  • It is internal class in framework with above structure. i would like to Create instance of the class using constructor/static method and after that use the MethodInfo to use the methods in the class. object mc = assembly.CreateInstance( ---- <- unable to use it as it has private constructor MethodInfo mi = type1.GetMethod( "MyMethod", bf );
    – sunny
    Jan 7, 2010 at 20:09

5 Answers 5

29

EDIT: I hadn't noticed that you mentioned that the type you're trying to initialize is part of the .NET framework. I thought it was one of your own types, just referenced from elsewhere.

I would strongly urge you not to attempt this. Microsoft are perfectly at liberty to change or remove internal classes between framework releases - your code will be incredibly brittle if you rely on implementation details like this.

Change your design to avoid needing to do this.


Original answer:

Yes, you'd have to use reflection - like this:

using System;
using System.Reflection;

internal sealed class ABC
{
    private ABC(string password)
    {
        Console.WriteLine("Constructor called");
    }
}

public class Test
{
    static void Main()
    {
        ConstructorInfo ctor = typeof(ABC).GetConstructors
            (BindingFlags.Instance | BindingFlags.NonPublic)[0];

        ABC abc = (ABC) ctor.Invoke(new object[] { "test" });
    }
}

Note that violating access modifiers in this way requires the ReflectionPermissionFlag.MemberAccess permission. If you know there will be a static method called Create, you'd be better off invoking that via reflection:

using System;
using System.Reflection;

internal sealed class ABC
{
    private ABC(string password)
    {
        Console.WriteLine("Constructor called");
    }

    public static ABC Create(string password)
    {
        return new ABC(password);
    }
}

public class Test
{
    static void Main()
    {
        MethodInfo method = typeof(ABC).GetMethod("Create",
            BindingFlags.Static | BindingFlags.Public);

        ABC abc = (ABC) method.Invoke(null, new object[]{"test"});
    }
}
2
  • 2
    If the ABC type is internal in another assembly, he will need to get the type by its FullName.
    – Jeff Cyr
    Jan 7, 2010 at 20:01
  • Thanks everyone for your comments. I will find another way to do it. It is a valid point that MS can change it! thanks again
    – sunny
    Jan 7, 2010 at 21:03
24

First of all, the very fact that it is internal means you're not supposed to be doing what you want to do.

You should seriously try to find an alternate route to what you want to accomplish.

Unfortunately, you don't tell us what you want to accomplish, only the next step you think you want to do, so that's what I can help you with.

This code will work, and accesses the public static method:

Type t = typeof(SomeOtherTypeInSameAssembly)
    .Assembly.GetType("ClassLibrary1.ABC");
MethodInfo method = t.GetMethod("Create",
    BindingFlags.Public | BindingFlags.Static, null,
    new Type[] { typeof(String) },
    new ParameterModifier[0]);
Object o = method.Invoke(null, new Object[] { "test" });

Note that this relies on having access to another type in the same assembly, that is public. If you don't have that, you need to get hold of the Assembly object that contains the type.

3
  • 10
    First of all, the very fact that it is internal means you're not supposed to be doing what you want to do. what about making a unit testing but keep the class isolation?
    – ktutnik
    Jun 23, 2012 at 4:19
  • 23
    The very fact that someone needs to access internal classes and is aware of specific internal classes actually demonstrates that they're probably intelligent enough to open Reflector and decide for themselves whether doing so would be useful or a good idea. Code is code, and an "internal" modifier is nothing more than a kind of DRM to be circumvented, IMO.
    – Triynko
    Oct 3, 2012 at 21:15
  • 4
    @ktutnik: with unit test this is usually achieved with InternalsVisibleToAttribute Jun 28, 2013 at 7:19
4

If it's internal to an assembly that is not yours and the constructor is marked as private, the author of the assembly is trying very hard to keep you from creating the object.

The below is really evil as you're relying on non-public classes and methods which could change on you without advance notice.

Added: System.ServiceModel.Channels.SelfSignedCertificate is the internal class I am trying to use

Do not do this. The framework could change under you in the blink of an eye ruining your code and all of your hard work.

That said, you could do this:

MethodInfo method = Type.GetType(assemblyQualifiedName).GetMethod("Create");
ABC o = (ABC)method.Invoke(null, new[] { "test" });

This invokes the static method Create. Another option is

MethodInfo method = Type.GetType(assemblyQualifiedName).GetConstructor(
                        BindingFlags.NonPublic | BindingFlags.Instance,
                        null,
                        new[] { typeof(string) },
                        null
                    );
ABC o = (ABC)method.Invoke(new[] { "test" });

which uses reflection to load the constructor that accepts a string as a parameter.

An easy way to get the assembly-qualified name is

string name = typeof(somePublicType).Assembly.GetType("Namespace.ABC");

where somePublicType is a type that is public and in the same assembly as ABC.

3
  • I do not have the access to ABC so can not use MethodInfo method = typeof(ABC). I used reflector and saw this class in framework. I need to use it.
    – sunny
    Jan 7, 2010 at 20:11
  • If the framework designer wanted the class to be used by consumers of the framework, there would be some other way to get an instance of the object without resorting to this kind of hackery.
    – Jon Seigel
    Jan 7, 2010 at 20:23
  • @unknown(google): You have to use the assembly-qualified name. See my edit.
    – jason
    Jan 7, 2010 at 20:34
1

Use the Activator class to instantiate it

Activator.CreateInstance(myType, true);
2
  • Error: Could not load file or assembly 'System.ServiceModel.Channels' or one of its dependencies. The system cannot find the file specified.
    – sunny
    Jan 7, 2010 at 20:17
  • Activator.CreateInstance(internalType, new object[] {null, null}) In my case constructor takes 2 parameters. It works for me.
    – marbel82
    Sep 3, 2020 at 13:52
-1

You can't instantiate classes with private constructors unless it's a nested class.

http://msdn.microsoft.com/en-us/library/kcfb85a6%28VS.71%29.aspx

4
  • Not true, with reflection everything is possible if you have enough rights.
    – Jeff Cyr
    Jan 7, 2010 at 19:59
  • But do you have enough rights if the class is sealed internal?
    – Matt
    Jan 7, 2010 at 20:03
  • You can instantiate it from within the class using a static method. Jan 7, 2010 at 20:03
  • @Matt: If you've got ReflectionPermissionFlag.MemberAccess, yes.
    – Jon Skeet
    Jan 7, 2010 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.