Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reflection to determine if a class is internal?

Tags:

c#

reflection

As the title says, how do you use reflection to check if a class definition is defined as internal? "typeof(...)" returns certain properties shown below but not whether a class is defined as internal. Looked on Google but all I could find were lots of articles about running internal or protected methods using reflection. It's not the methods I'm interested in this case, but the class definition.

var type = typeof(Customer); Assert.IsTrue(type.IsClass); Assert.That(type.IsAbstract, Is.EqualTo(isAbstract)); Assert.That(type.IsPublic, Is.EqualTo(isPublic)); Assert.That(type.IsPublic, Is.EqualTo(isPublic)); Assert.That(type.IsSealed, Is.EqualTo(isSealed)); Assert.That(type.IsSerializable, Is.EqualTo(isSerializable)); 
like image 643
Paul Hadfield Avatar asked Feb 11 '11 16:02

Paul Hadfield


People also ask

Where do we use reflection in C#?

Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.

How does C# reflection work?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Can we access private methods using reflection C#?

Using reflection in C# language, we can access the private fields, data and functions etc.


2 Answers

This is a classic issue. From MSDN:

The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.

Reflection does not expose a way on Type check if it is internal, protected or protected internal.

like image 120
jason Avatar answered Sep 19 '22 03:09

jason


Does the IsVisible method give you the value you are looking for?

like image 31
John Koerner Avatar answered Sep 21 '22 03:09

John Koerner