Allow DynamicallyAccessedMembersAttribute on methods #36708
Labels
api-approved
API was approved in API review, it can be implemented
area-System.Runtime
linkable-framework
Issues associated with delivering a linker friendly framework
Background and Motivation
The
DynamicallyAccessedMembersAttribute
is used to annotate "data things" (method parameters, fields, return values, ...) of typeSystem.Type
andSystem.String
. Adding the attribute means that the code may access some members on the type in question (represented either asSystem.Type
or as the type name inSystem.String
) using reflection or similar APIs. We plan to use these attribute to annotate reflection APIs themselves, so for exampleActivator.CreateInstance(Type type)
will have the attribute on thetype
parameter marking it to need default constructor.But some reflection APIs will need to put this annotation onto the "this" parameter. For example
Type.GetFields()
- should haveDynamicallyAccessedMembers[DynamicallyAccessedMemberType.PublicFields]
on the "this" parameter.C# doesn't have a way to add attribute to the "this" parameter, so there needs to be some other way to this.
The
DynamicallyAccessedMembersAttribute
addition has been discussed here: #33861.Proposed API
Allow the
DynamicallyAccessedMembersAttribute
to be applied to methods, the meaning would be that it applies to the "this" parameter. Tools would only recognize the attribute on methods on types derived fromSystem.Type
and would issue a warning if such attribute is found on a method on any other type.Usage Examples
Alternative Designs
Alternative is to introduce a new attribute type just for this case which would otherwise look exactly like the
DynamicallyAccessedMembersAttribute
. Possible names could beDynamicallyAccessedMembersOnThisAttribute
. The semantics of such attribute would be exactly the same as those described above forDynamicallyAccessedMembersAttribute
on method.Risks
Allowing the
DynamicallyAccessedMembersAttribute
on methods may lead to users incorrectly adding it onto the method when they meant to put it onto either a method parameter or the return value of a method since compiler would not complain about such usage.This will be partially mitigated by the tools (IL Linker) warnings about such cases.
In the future we can also mitigate this better by having a Roslyn analyzer detect such cases and warn about them directly in the IDE.
The text was updated successfully, but these errors were encountered: