How to access internal class using Reflection

C#ReflectionClassInternal

C# Problem Overview


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?.

C# Solutions


Solution 1 - C#

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).

Solution 2 - C#

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondattebayoView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#Patrick McDonaldView Answer on Stackoverflow