Skip to content

Trim analysis doesn't understand receiver type for calls to GetType() #100786

Closed as not planned

Description

@sbomer

DynamicallyAccessedMembers annotations on a type will treat the return value of GetType as satisfying the annotation, for a call to this.GetType(), but not for a call to c.GetType() where c is assignable to the annotated type.

This causes a warning on the call to Require(c.GetType()) in the sample below. It's possible to work around this by defining an annotated helper on the type that just returns this.GetType(), but this ideally wouldn't be necessary:

using System.Diagnostics.CodeAnalysis;

C c = new();
Require(c.GetType()); // Warning

Require(c.GetTypeWithConstructors()); // OK

static void Require([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type type) {}

[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]
class C {
    [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]
    public Type GetTypeWithConstructors() => GetType();
}

Activity

  1. dotnet-policy-service commented on Apr 8, 2024

    @dotnet-policy-service
    Contributor

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

  2. added
    untriaged
    on Apr 8, 2024
  3. vitek-karas commented on Apr 8, 2024

    @vitek-karas
    Member

    This is basically the same issue as #93720, also combined with the fact that trimmer doesn't track return values of new (as in it doesn't know the static type of it, although it could) - there's another bug for that one, but I can't find it now.

    The current state of the comments on the other issue is that typed stack would fix this for the declared variable type. It would not fix the new issue though.

  4. sbomer commented on Apr 8, 2024

    @sbomer
    MemberAuthor

    Thanks, I thought there was some discussion but was having trouble finding an existing issue. Closing this as a duplicate of #93720.

  5. removed
    untriaged
    on Apr 8, 2024
  6. reopened this on Apr 8, 2024
  7. added
    untriaged
    on Apr 8, 2024
  8. sbomer commented on Apr 8, 2024

    @sbomer
    MemberAuthor

    Dup of #93720

  9. removed
    untriaged
    on Apr 8, 2024
  10. locked and limited conversation to collaborators on May 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions