sonar-dotnet
sonar-dotnet copied to clipboard
Fix S3011 FN: Support UnsafeAccessorAttribute
While S3011 explicitly talks about using reflection to get access to members that otherwise could not be accessed by direct dereference, the focus of the rule is on increased accessibility, and reflection is just a way to achieve that.
The C# 12 Zero-overhead member access is a new way of achieving the same result, but without using reflection.
using System.Runtime.CompilerServices;
[UnsafeAccessor(UnsafeAccessorKind.Constructor)]
extern static UserData<T> CallPrivateConstructor<T>();
// This API allows accessing backing fields for auto-implemented properties with unspeakable names
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "<Name>k__BackingField")]
extern static ref string GetName<T>(UserData<T> obj);
UserData<string> ud = CallPrivateConstructor<string>();
ref string x = ref GetName(ud);
x = "Name";
Console.WriteLine(x);
Console.WriteLine(ud);
class UserData<T>
{
private UserData() { }
private T Name { get; }
public override string ToString() => Name.ToString();
}
The rule should be extended to take into account this new feature.
An alternative would to create a dedicated rule for UnsafeAccessorAttribute
.
Related New Rule Idea: https://github.com/SonarSource/sonar-dotnet/issues/8151