sonar-dotnet
sonar-dotnet copied to clipboard
New Rule Idea: UnsafeAccessorAttribute should define a valid name
The Name
parameter of the UnsafeAccessorAttribute
should be:
- not specified, when kind is
UnsafeAccessorKind.Constructor
- the name of an existing member (including unspeakable fields), when kind is
UnsafeAccessorKind.Method
,UnsafeAccessorKind.StaticMethod
,UnsafeAccessorKind.Field
orUnsafeAccessorKind.StaticField
Not respecting this rule would result in a System.BadImageFormatException: 'Invalid usage of UnsafeAccessorAttribute.'
.
using System.Runtime.CompilerServices;
[UnsafeAccessor(UnsafeAccessorKind.Constructor, Name = "AnInvalidName")] // Noncompliant: Name should not be specified with kind Constructor
extern static UserData CallCtor();
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "NonExistingMethod")] // Noncompliant: There is no "NonExistingMethod" in UserData
extern static void CallMethod();
CallCtor(); // BadImageFormatException
CallMethod(); // BadImageFormatException
class UserData
{
private UserData() { }
}
nameof
is not usable in most scenarios, since the member being targeted by the UnsafeAccessorAttribute
is private
, hence it cannot be referenced inside the nameof
.
Related new rule ideas on C# 12 Zero-overhead member access:
- https://github.com/SonarSource/sonar-dotnet/issues/8151
- https://github.com/SonarSource/sonar-dotnet/issues/8154