When I declare a class as internal, why does IL show it as private?

If I declare a class as internal, why does IL show it as private?

internal class Thing .class private auto ansi beforefieldinit Thing.Thing extends [mscorlib]System.Object 
+4
source share
3 answers

From the point of view of IL, private means private for the assembly, i.e. internal in C #.

In C #, you cannot mark types as private unless they are nested . IL equivalent accessibility for such nested private types.

So we have:

  • C # internal IL private (to assembly)
  • C # private IL nested private (to enclosing type)
+10
source

The MSDN says:

C # keywords, protected and internal, are not relevant in IL and are not used in the reflection API. Relevant members in the IL Family and Assembly. To identify the internal method using reflection, use the IsAssembly property. To define a protected internal method, use IsFamilyOrAssembly.

Therefore, I suppose that it simply makes them closed, since they cannot be accessed from other places.

EDIT: I see how my answer may not be entirely correct, I just thought it was something worth noting. The MSDN article I linked has some interesting things in this "what we write" - "what it will be."

+4
source

Matching C # keywords with IL keywords is not always logical. Ecma-335, section II.23.1.15 shows which flags are valid for the type. You will see that it only defines Public, NotPublic, and the NestedXxx flag set. Nothing like "inner." Thus, your class is actually NotPublic, displayed as "private" in ildasm.

It's easy to see a side effect of this: try this ad in C # code:

 private class DoesNotWork { } 

You'll get:

error CS1527: Elements defined in the namespace cannot be explicitly declared as private, protected, or protected internal

+3
source

Source: https://habr.com/ru/post/1500945/


All Articles