Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access internal class using Reflection

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

like image 972
dattebayo Avatar asked Aug 11 '09 09:08

dattebayo


People also ask

How do you access an internal class in another project?

You can use the InternalsVisibleTo attribute and provide the name of a specific assembly that can see the internal types in your assembly. That being said.. I think you are bordering on over-designing this. If the Settings class belongs only to Assembly A... don't put it in Assembly B...

Can internal class have public members?

Class, record, and struct member accessibility However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.

What is System reflection?

Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types. Some of the commonly used classes of System.Reflection are: Class.


2 Answers

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

like image 53
Jon Skeet Avatar answered Sep 19 '22 00:09

Jon Skeet


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"); 
like image 39
Patrick McDonald Avatar answered Sep 19 '22 00:09

Patrick McDonald