SonarSource/sonar-dotnet

Fix S1144 FP: Diagnostic doesn't respect reflection with `DynamicallyAccessedMembers` attribute

Closed this issue · 2 comments

Description

Diagnostic S1144 doesn't respect reflection even though the generic parameter is annotated with the DynamicallyAccessedMembers attribute.

Related: #7774

Repro steps

This is a minified repro. In my actuall use case I called UseMiddleware.

using System.Diagnostics.CodeAnalysis;

namespace SonarCubeRepro
{
    internal static class Program
    {
        static void Main()
        {
            var instance = CreateInstance<Foo>();
            Console.WriteLine( instance.Number );
        }

        public static T CreateInstance<[DynamicallyAccessedMembers( DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors )] T>()
        {
            var instance = (T)Activator.CreateInstance( typeof( T ), 42 )!;
            return instance;
        }

        private sealed class Foo
        {
            public Foo( int number )
            {
                Number = number;
            }

            public int Number { get; set; }
        }
    }
}

Expected behavior

No warning.

Actual behavior

Warning S1144

Known workarounds

Supress the issue

Related information

SonarAnalyzer.CSharp Version=9.26.0.92422

  • C#/VB.NET Plugins version
  • Visual Studio version: 17.9.6
  • MSBuild / dotnet version: 8.0.204
  • SonarScanner for .NET version (if used)
  • Operating System: Windows 10

Thank you for reporting the issue. Confirmed as False Positive.

@dotjpg3141 It turns out fixing the issue for generic method calls seriously degrades the analyzer performance, so we opted not to fix this scenario and instead document it as a False Positive.
The analyzer can still be prompted to ignore a type or a member by decorating it with the DynamicallyAccessedMembersAttribute: either by decorating it with the System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute (available in .NET 5.0+) or by your own custom attribute named DynamicallyAccessedMembersAttribute (in .NET Framework projects).
This change will be available in the next release (9.28).