SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
770 stars 226 forks source link

New Rule Idea: UnsafeAccessorAttribute should not be used on generic methods #8151

Open antonioaversa opened 11 months ago

antonioaversa commented 11 months ago

Related to C# 12 Zero-overhead member access.

Using UnsafeAccessorAttribute on generic methods results in a System.BadImageFormatException Invalid usage of UnsafeAccessorAttribute.

using System.Runtime.CompilerServices;

[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
extern static UserData<T> CallPrivateConstructor<T>();

_ = CallPrivateConstructor<string>(); // Noncompliant, results in a BadImageFormatException

class UserData<T>
{
    private UserData() { }
    private T Name { get; }
}

Related new rule ideas on C# 12 Zero-overhead member access:

RichardD2 commented 5 months ago

Annoyingly, the examples in the documentation for .NET 8.0 explicitly show this attribute being used on generic methods, and methods in generic classes.

It's only when you read further down that you see:

Generic parameters are supported since .NET 9.