Skip to content

Linker warns about compiler generated fields when using new reflection attributes #1403

@davidfowl

Description

@davidfowl

Consider the following:

using System;
using System.Diagnostics.CodeAnalysis;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Create(typeof(Person));
        }

        static object Create([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]Type t)
        {
            object Foo()
            {
                return Activator.CreateInstance(t);
            }

            return Foo();
        }
    }

    public class Person
    {
        public int Age { get; set; }
    }
}

It'll result in the following warning:

C:\Users\davifowl\source\repos\WebApplication60\ConsoleApp1\Program.cs(17,17): Trim analysis warning IL2006: ConsoleApp1.Program.<Create>g__Foo|1_0(<>c__DisplayClass1_0&): The field 'System.Type ConsoleApp1.Program/<>c__DisplayClass1_0::t' with dynamically accessed member kinds 'None' is passed into the parameter #0 of method 'System.Object System.Activator::CreateInstance(System.Type)' which requires dynamically accessed member kinds 'PublicParameterlessConstructor'. To fix this add DynamicallyAccessedMembersAttribute to it and specify at least these member kinds 'PublicParameterlessConstructor'. [C:\Users\davifowl\source\repos\WebApplication60\ConsoleApp1\ConsoleApp1.csproj]

Which makes sense but I can't annotate the closure fields since they are compiler generated. The linker warnings needs to be disabled for compiler generated types (or inferred as having the attribute which is really the same thing).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions