91

How can I access an internal class of an assembly? Say I want to access System.ComponentModel.Design.DesignerHost. Here the DesignerHost is an internal and sealed class.

How can I write a code to load the assembly and the type?.

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
dattebayo
  • 2,012
  • 4
  • 30
  • 40

2 Answers2

124

In general, you shouldn't do this - if a type has been marked internal, that means you're not meant to use it from outside the assembly. It could be removed, changed etc in a later version.

However, reflection does allow you to access types and members which aren't public - just look for overloads which take a BindingFlags argument, and include BindingFlags.NonPublic in the flags that you pass.

If you have the fully qualified name of the type (including the assembly information) then just calling Type.GetType(string) should work. If you know the assembly in advance, and know of a public type within that assembly, then using typeof(TheOtherType).Assembly to get the assembly reference is generally simpler, then you can call Assembly.GetType(string).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 10
    @dattebayo : just to complete Jon's answer, note that your code needs to run in full trust, or reflection on non-public members will fail – Thomas Levesque Aug 11 '09 at 09:21
  • 6
    Sometimes you just have to, until it breaks. I have a WPF `DataGrid` command whose parameter is `SelectedItems`. In the command, the parameter is received as `object` but it of type `SelectedCellCollection`, which is inaccessible in my code. I need this kind of cheat in the hope of casting the `object` parameter to a `SelectedCellCollection`. – ProfK Dec 08 '16 at 14:28
19

To load the assembly and type you quoted in your example:

Assembly design = Assembly.LoadFile(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll");
Type designHost = design.GetType("System.ComponentModel.Design.DesignerHost");
Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
  • 11
    You can just `Assembly.Load("System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")` – abatishchev Feb 02 '11 at 07:27
  • 7
    If you only need one type you can skip loading the assembly explicitly: `var designHost = Type.GetType("System.ComponentModel.Design.DesignerHost, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");` – Max Truxa Apr 25 '14 at 08:39