Zsolt Kolbay 33e7a76421
Modify S3993: Promote C# rule to Sonar-way (#4130)
* Promote S3993 to Sonar-way and convert to LayC format

* Add missing newline to S2674

* Address comments
2024-08-09 13:40:23 +02:00

66 lines
1.6 KiB
Plaintext

== Why is this an issue?
When defining custom attributes, https://learn.microsoft.com/en-us/dotnet/api/system.attributeusageattribute[AttributeUsageAttribute] must be used to indicate where the attribute can be applied. This will:
* indicate how the attribute can be used
* prevent it from being used at invalid locations
== How to fix it
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public sealed class MyAttribute : Attribute // Noncompliant - AttributeUsage is missing
{
private string text;
public MyAttribute(string text)
{
this.text = text;
}
public string Text => text;
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)]
public sealed class MyAttribute : Attribute
{
private string text;
public MyAttribute(string text)
{
this.text = text;
}
public string Text => text;
}
----
== Resources
=== Documentation
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/creating-custom-attributes[Create custom attributes]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.attributeusageattribute[AttributeUsageAttribute class]
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/api/system.attribute[Attribute class]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
endif::env-github,rspecator-view[]