Skip to content

[API Proposal]: Make DynamicallyAccessedMembers valid for Type/string collection parameters #131394

Description

@koszeggy

Background and motivation

[DynamicallyAccessedMembers] is valid for pure Type/string parameters, but not for collections, whose element type is Type or string.

Consider the following example:

// In safe mode polymorphic deserialization does not resolve type names in the serialization stream,
// even if they present with their assembly qualified name. All types that are not supported natively
// by the serializer must be enlisted in the expectedCustomTypes parameter.
// TRoot (along with its type arguments if it is a generic type) are automatically included in expectedCustomTypes
public TRoot DeserializeSafe<TRoot>(XmlReader reader, params Type[] expectedCustomTypes)
{
    // [...]
{

As of today, such an API cannot be made AOT-compatible, because I can apply [DynamicallyAccessedMembers] for TRoot only, but not for expectedCustomTypes:

warning IL2098: Parameter 'expectedCustomTypes' of method 'DeserializeSafe`1(XmlReader, params Type[])' has 'DynamicallyAccessedMembersAttribute', but that attribute can only be applied to parameters of type 'System.Type' or 'System.String'.

API Proposal

No actual change is needed for the DynamicallyAccessedMembersAttribute - the change affects the trimming only

API Usage

By accepting the proposal, this would become valid:

private const DynamicallyAccessedMemberTypes neededMembers = DynamicallyAccessedMemberTypes.AllConstructors
    | DynamicallyAccessedMemberTypes.PublicFields
    | DynamicallyAccessedMemberTypes.PublicProperties;

public TRoot DeserializeSafe<[DynamicallyAccessedMembers(neededMembers)]TRoot>( // nothing new here
  XmlReader reader,
  [DynamicallyAccessedMembers(neededMembers)]params Type[] expectedCustomTypes) // no IL2098 anymore
{
    // [...]
{

And then an AOT-friendly usage could use typeof() expressions passed to the expectedCustomTypes parameter:

var myObj = xmlSerializer.DeserializeSafe<MySerializableObject>(xmlStream, typeof(MyEmbeddedType1), typeof(MyEmbeddedType2));

Alternative Designs

Risks

?

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Reflectionlinkable-frameworkIssues associated with delivering a linker friendly framework

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions