Repository navigation
Description
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,FullNameandToString()return a placeholder;GUIDandAssemblyQualifiedNamethrowNotSupportedException(so doesAssemblyon Native AOT);Type.GetType(string)andAssembly.GetType(string)do not find it andGetTypes()does not list it;Activator.CreateInstancefails; - the non public members (private, internal, protected, protected internal, private protected, explicit interface implementations, backing fields) of any type are hidden: the
BindingFlags.NonPublicmembers are not returned byGetMethods,GetFields,GetProperties,GetEvents,GetConstructors,GetMember(s)andGetNestedTypes, binding by name does not find them, and handles to them (ldtoken,Delegate.Method) cannot be converted toMethodBaseorFieldInfo. 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,IDynamicInterfaceCastableimplementations, 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, byGetCustomAttributes,IsDefinedandCustomAttributeData, 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,DiagnosticMethodInfoand the debugger show the real names, also for hidden types and members (andException.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()andException.TargetSitearenullfor 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
- A new per type attribute ([API Proposal]: ReflectionBlockedAttribute to remove the reflection metadata of types that nothing reflects over #138057). Needs a new public API, is Native AOT only, and CoreCLR would either ignore it or need to emulate it. Reusing the existing attribute gives an assembly level opt in with the same behavior on both runtimes.
- Let ILC infer it. A constructed type always gets metadata, and its name is observable without any reflection API (
Object.ToString(), exception messages). Escape analysis forGetTypeis out of reach for ILC. - A global switch (reflection-free mode, removed in Delete reflection-free mode #109857, and blocked types, removed in Get rid of reflection blocked types #85810). All or nothing, and it changes the output of unrelated code that prints type names.
- Not constructing the helper types in CsWinRT. A large redesign of the generated code, and it does not help types that have to exist as generic arguments.
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.CreateInstanceon an internal type,GetFieldon a private field, source generated COMComWrappersdetails 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 byobject.ToString()of its instances. The messages that the CoreCLR runtime formats itself (InvalidCastException,TypeLoadException) and the exception type name inException.ToString()keep the real name on CoreCLR, the ones that Native AOT formats have the placeholder.StackFrame.GetMethod()returnsnullfor 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:
MakeGenericTypeabout +4% (about 7 ns),CustomAttributeData+5% (about 16 ns),Type.GetType(string)of a framework type +5%,GetBaseDefinition+5%,IsDefinedandAssembly.GetTypeabout +2.5%;Activator.CreateInstance(Type)and the member lists are within noise. - Other known limits are in the design document: no
AppContextopt-out;Reflection.Emitassemblies 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
dotnet-policy-service commentedon Nov 23, 2026
Tagging subscribers to this area: @steveisok, @dotnet/area-system-reflection
See info in area-owners.md if you want to be subscribed.
jkotas commentedon Nov 23, 2026
Reflection of any non-public members is private reflection. This is in conflict with what the attribute name says.
I do not think this attribute should affect diagnostic features. All diagnostics features (stacktraces, debugger funceval, ...) should work the same way.
That sounds like a bug in your prototype.
Sergio0694 commentedon Nov 23, 2026
Addressed all 3, will update the issue description too. Same size savings when combined with
StackTraceSupport=false, as expected.