Skip to content

[API Proposal]: Make DisablePrivateReflectionAttribute non obsolete and hide non public types from reflection #138108

Description

@Sergio0694

Background and motivation

System.Runtime.CompilerServices.DisablePrivateReflectionAttribute is an assembly level attribute from .NET Framework 4.5 that makes the non public types and members of an assembly unavailable to reflection. It has had no effect since .NET Core 2.1 and is marked [Obsolete] (SYSLIB0015).

This proposes to remove the [Obsolete] and give the attribute an effect in Native AOT and CoreCLR: the non public types and the non public members of the annotated assembly are hidden from reflection, as the name says. Diagnostics (stack traces, the debugger) are not affected.

In Native AOT, ILC makes a type reflection visible (a type definition with its members, custom attributes and stack trace names in the metadata) for many reasons the program cannot influence: every constructed type, every type argument of a reflectable generic instantiation, attribute classes, type map values and so on. Members are kept too, for example when a type is a dynamically accessed type argument or an attribute class. A library that knows nothing will ever reflect over its implementation details has no way to say so. CsWinRT 3.0 is the motivating case: it generates thousands of helper types (vtable helpers, marshallers, *Methods classes, IDynamicInterfaceCastable implementations) that are only ever called, and most of them end up with metadata in the binary. With the attribute, the library states once per assembly that its non public types and members are implementation details, and the compiler drops their metadata.

CoreCLR gets nearly the same behavior (it is more permissive in the few cases listed in the fidelity table of the design document), so that a library behaves alike in development and when published.

Measured on the Microsoft Store (Native AOT, OptimizationPreference=Size), on top of the typed type map values (#138056, #138065) and the ILC type loader gate (#137541):

WinStore.App.dll MSIX (estimated)
Before (typed values, no attribute) 82,376,192 27,012,840
After 81,507,328 (-868,864, -1.05%) 26,861,600 (-151,240)

The MSIX column is the image compressed at zlib level 6, as a proxy for its size in the package. It is not a measured MSIX build. All the measured builds have stack trace support off. The "After" build uses CsWinRT 3.0 emitting the attribute in its generated assemblies, with the helper types internal and the few types read by the COM source generated attributes public. If stack trace support is on, keeping the real names of hidden types in stack traces costs about 2.8 MB (+2.85%) on this app compared with dropping them. Hiding the non public members of the remaining visible types showed no measurable change on this app (the cause was not isolated).

This is part of #137567.

API Proposal

No change in API shape: the existing attribute becomes non obsolete (SYSLIB0015 is retired).

 namespace System.Runtime.CompilerServices;

 [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
-[Obsolete("DisablePrivateReflectionAttribute has no effect in .NET 6.0+.", DiagnosticId = "SYSLIB0015", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]
 public sealed class DisablePrivateReflectionAttribute : Attribute
 {
     public DisablePrivateReflectionAttribute();
 }

In an assembly that has the attribute:

  • a type that is not externally visible (not public, or nested in a type that is not public) is hidden: it has no members, nested types or custom attributes; Type.Name, FullName and ToString() return a placeholder; GUID and AssemblyQualifiedName throw NotSupportedException (so does Assembly on Native AOT); Type.GetType(string) and Assembly.GetType(string) do not find it and GetTypes() does not list it; Activator.CreateInstance fails;
  • the non public members (private, internal, protected, protected internal, private protected, explicit interface implementations, backing fields) of any type are hidden: the BindingFlags.NonPublic members are not returned by GetMethods, GetFields, GetProperties, GetEvents, GetConstructors, GetMember(s) and GetNestedTypes, binding by name does not find them, and handles to them (ldtoken, Delegate.Method) cannot be converted to MethodBase or FieldInfo. A property or event is available if one of its accessors is;
  • everything works for the program: instances, casts, GetType(), typeof, calls, delegates, virtual and interface dispatch, static abstract members, type maps, IDynamicInterfaceCastable implementations, and [UnsafeAccessor] (which does not use reflection) on hidden types and members;
  • the custom attributes of a type or member that is available are returned, also when they mention a hidden type (generic argument, typeof, array; the hidden type is surfaced as a hidden type); a custom attribute whose attribute class is hidden is not returned, by GetCustomAttributes, IsDefined and CustomAttributeData, in any assembly;
  • enums, delegates, top-level attribute classes (the runtime instantiates them), generic types and types with generic virtual methods (the runtime needs their metadata) stay available, and so do the types that contain one of these as a nested type. Their non public members are hidden too, except for all the members of enums and delegates and the constructors, fields and properties of attribute classes. Mono is not affected;
  • diagnostics are not affected: stack traces, Environment.StackTrace, DiagnosticMethodInfo and the debugger show the real names, also for hidden types and members (and Exception.ToString() shows the real exception type name on CoreCLR). On Native AOT this keeps the stack trace names of hidden types in the stack trace data, and only if the stack trace support is on. StackFrame.GetMethod() and Exception.TargetSite are null for a hidden method.

Both runtimes match the attribute by namespace and name, so a library can declare its own copy. Native AOT also strips the metadata of the hidden types and members; CoreCLR reads the attribute once per module. The full rules and the fidelity table between the runtimes are in the design document of the implementation (#138109).

API Usage

[assembly: DisablePrivateReflection]

public class Widget
{
    public int Id { get; }

    // Hidden from reflection (and its metadata dropped from a Native AOT binary), but it works for the program
    private int Compute() => 42;
}

// A hidden type: no members, no custom attributes, placeholder name.
// Instances, casts, GetType() and typeof still work.
internal sealed class WidgetMarshaller
{
    public static nint Marshal(Widget value) => 0;
}

Alternative Designs

Risks

  • Behavior change for assemblies that carry the attribute: it had no effect since .NET Core 2.1. Code that reflects over non public types or members of such an assembly (reflection based serializers, DI activation, Activator.CreateInstance on an internal type, GetField on a private field, source generated COM ComWrappers details read through attributes on internal types) stops working and needs the types and members to be public. [UnsafeAccessor] still works.
  • A hidden type is named with a placeholder by Type.ToString(), and so by object.ToString() of its instances. The messages that the CoreCLR runtime formats itself (InvalidCastException, TypeLoadException) and the exception type name in Exception.ToString() keep the real name on CoreCLR, the ones that Native AOT formats have the placeholder. StackFrame.GetMethod() returns null for a hidden method, so tools that read frames through it (some loggers and exception pages) see no method for them.
  • CoreCLR cost on the reflection hot paths of assemblies that do not use the attribute is module flag reads: MakeGenericType about +4% (about 7 ns), CustomAttributeData +5% (about 16 ns), Type.GetType(string) of a framework type +5%, GetBaseDefinition +5%, IsDefined and Assembly.GetType about +2.5%; Activator.CreateInstance(Type) and the member lists are within noise.
  • Other known limits are in the design document: no AppContext opt-out; Reflection.Emit assemblies are not covered on CoreCLR; the Native AOT debugger display of a timer or task with a hidden callback.

Note

This issue was drafted with AI assistance (GitHub Copilot) and reviewed by the author. A draft PR with the implementation is #138109.

Activity

  1. added
    api-suggestion
    on Nov 23, 2026
  2. added
    untriaged
    on Nov 23, 2026
  3. dotnet-policy-service commented on Nov 23, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @steveisok, @dotnet/area-system-reflection
    See info in area-owners.md if you want to be subscribed.

  4. jkotas commented on Nov 23, 2026

    @jkotas
    Member

    public types and their non public members are not affected

    Reflection of any non-public members is private reflection. This is in conflict with what the attribute name says.

    Stack traces:

    I do not think this attribute should affect diagnostic features. All diagnostics features (stacktraces, debugger funceval, ...) should work the same way.

    Other known limits are in the design document: CustomAttributeData throws on CoreCLR (instead of hiding the attribute)

    That sounds like a bug in your prototype.

  5. Sergio0694 commented on Nov 23, 2026

    @Sergio0694
    ContributorAuthor

    Addressed all 3, will update the issue description too. Same size savings when combined with StackTraceSupport=false, as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Reflectionuntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions